Angular 类型“AbstractControl”缺少“FormGroup”类型中的以下属性:

时间:2021-05-03 08:46:30

标签: angular typescript angular-material angular-reactive-forms

我在研究 Angular FormArray,因此我在研究本教程:https://www.youtube.com/watch?v=aOQ1xFC3amw 不幸的是,我无法应用该教程。我的 HTML 部分出错。

我使用 Angular 11

这是我显示错误消息的 HTML:

    <div [formGroup]="myForm">
         <ng-container formArrayName="demoTypes">

                <ng-container *ngFor="let demoForm of demoFormArray.controls">

                    <div [formGroup]="demoForm"><!--formGroup is as error underlined-->
                       
                    </div>

                </ng-container>

         </ng-container>
    </div>

错误信息是:

<块引用>

“AbstractControl”类型缺少“FormGroup”类型中的以下属性:controls、registerControl、addControl、removeControl 等。

这是我的 TypeScript 类:


    export class DemoComponent implements OnInit {

        myForm!: FormGroup;

        constructor(private formBuilder: FormBuilder) { }

        ngOnInit(): void {
            this.createForm();
        }

        createForm() {
            this.myForm = this.formBuilder.group({
                demoTypes: new FormArray([]),
            });

            this.addDemoTypes();
        }

        get demoFormArray() {
            return this.myForm.controls["demoTypes"] as FormArray;
        }

        addDemoTypes(): void {
            const demoControl = this.formBuilder.group({
                isChecked: new FormControl(true),
                demoFormControlName: new FormControl("This is the first one"),
            });
            this.demoFormArray.push(demoControl);
        }
    }

这里有什么问题?

[编辑] 在 tsconfig.json 中设置 "strictTemplates": false 解决了我的问题。但这是个好主意吗?

"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false
}

1 个答案:

答案 0 :(得分:1)

您可以使用 formGroupName 代替

  <ng-container *ngFor="let demoForm of demoFormArray.controls; let i = index">

    <div [formGroupName]="i">
                    
    </div>
</ng-container>

我们不会遇到打字稿错误,因为我们绑定到一个数字

禁用 strictTemplates

不要。启用 strictTemplates 后,您更有可能发现原本可以监控的问题。我认为把头埋在沙子里永远不能解决问题。你可能看不到危险,但危险还在