【问题标题】:Getting error while using Angular Form Array使用 Angular Form Array 时出错
【发布时间】:2022-12-14 14:17:42
【问题描述】:

为什么会出现此错误,以及如何修复它: TS2740:类型“AbstractControl<any, any>”缺少类型“FormGroup”中的以下属性:controls、registerControl、addControl、removeControl 等 2 个。

此时它在我的 html 中给出了错误:

我的 HTML:

<button type="button" (click)="addName()">Add Name</button>

<div formArrayName="names">
    <div *ngFor="let nm of getNames.controls">
        <div [formGroup]="nm"> //THIS LINE IS GIVING ERROR
            <input formControlName="fname" type="text" placeholder="First Name">
            <input formControlName="lname" type="text" placeholder="Last Name">
        </div>
    </div>
</div> 

<div>
    <button type="submit">Submit</button>
</div>

我的 ts:

export class TestComponent implements OnInit {     
    constructor(private fb: FormBuilder) { }

    form = this.fb.group({
        names: this.fb.array([])
    });

    get getNames(){
        return this.form.controls["names"] as FormArray;
    }

    addName(){
        const newName = this.fb.group({
            fname: ['', Validators.required],
            lname: ['', Validators.required]
        });
        this.getNames.push(newName);
    }

    onSubmit():void{
        console.log(this.form.value)
    }

   ngOnInit(): void {

   }

}

【问题讨论】:

    标签: angular-reactive-forms angular-forms angular-formbuilder


    【解决方案1】:

    我通过在 html 中使用 $any 解决了这个问题,如下所示。

    <div *ngFor="let nm of  $any(getName).controls; let i=index">
    

    【讨论】:

      【解决方案2】:

      嗨,我这样试试

       <div *ngFor="let nm of  getName.controls; let i=index" [formGroupName]="i">
      

      【讨论】:

        猜你喜欢
        • 2019-03-21
        • 2023-03-14
        • 2019-04-07
        • 2016-05-23
        • 2018-06-25
        • 1970-01-01
        • 2019-08-16
        • 2019-12-11
        • 1970-01-01
        相关资源
        最近更新 更多