Issue
I working on Angular FormArray, therefore I working on this tutorial: https://www.youtube.com/watch?v=aOQ1xFC3amw Unfortunately I can’t apply the tutorial. I got an error in my HTML part.
I use Angular 11
This is my HTML showing the error message:
<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>
The error message is:
Type 'AbstractControl' is missing the following properties from type 'FormGroup': controls, registerControl, addControl, removeControl, and 3 more.
This is my TypeScript class:
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);
}
}
What’s the problem here?
[EDIT]
Setting "strictTemplates": false
in tsconfig.json fixed my problem. But is this a good idea?
"angularCompilerOptions": {
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false
}
Solution
You can use formGroupName
instead
<ng-container *ngFor="let demoForm of demoFormArray.controls; let i = index">
<div [formGroupName]="i">
</div>
</ng-container>
We will not encounter the typescript error as we are binding to a number
Disabling strictTemplates
?
Don't. With enabled strictTemplates
you are more likely to catch problems that could otherwise have been overseen. I think burrying the head in the sand never solves the problem. You may not see the danger but the danger is still there
Answered By - Owen Kelvin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.