In a component at the typescript level, I created a form that contains a ControlForm that contains others, and I want to iterate it without success.
I would like to create an HTML (checkbox) element for each iteration on the controlForm 'test' and I would like to inject the name of each ControlForm child into each checkbox.
Here's the form:
public ngOnInit(): void {
this.fcTest = this.form.controls.test.value;
}
protected buildForm(): void {
// Form controls
this.form = this.formBuilder.group({
allowancesUntil90: [0, [Validators.required]],
test: this.formBuilder.group({
1: [false],
2: [false],
3: [false],
4: [false],
5: [false],
6: [false]
}, { validators: []})
});
}
And in the template:
<div *ngFor="let item of fcTest | keyvalue">
<amp-check-box [formControl] = form.controls.item ></amp-check-box>
</div>
I have the following error with this code : Argument type FormControl is not assignable to parameter type null
Thanks for your help
CodePudding user response:
According to the official Angular documentation on formBuilder
, the group()
method:
Construct a new FormGroup instance. Accepts a single generic argument, which is an object containing all the keys and corresponding inner control types
This means that inside a FormGroup
instance, all the keys should be either a FormControl
, a FormGroup
or a FormArray
. (in your case you are using a formControl
in the .html
so you need a FormControl
)
In your snippet, all the values that you are passing to the keys in the group()
method are an array of boolean. You may want to have values that are instances of FormControl
like an start incrementation from 0 (as index in arrays start with 0):
test: this.formBuilder.group({
0: this.formBuilder.control(false),
1: this.formBuilder.control(false),
2: this.formBuilder.control(false),
3: this.formBuilder.control(false),
4: this.formBuilder.control(false),
5: this.formBuilder.control(false)
}
Next, fcTest
should be a control, not the value of the control. So change ngOnInit
to this :
this.fcTest = this.form.controls.test
Then, another issue is located in your .html
file:
<div *ngFor="let item of fcTest | keyvalue">
<amp-check-box [formControl] = form.controls.item ></amp-check-box>
</div>
You want to acces the properties 0,1,2...5
defined in your .ts
file.
What you may want is:
<div *ngFor="let item of fcTest; let fcTestIndex=index">
<amp-check-box [formControl]=form.controls[fcTestIndex]></amp-check-box>
</div>
CodePudding user response:
As I see in your buildForm you are Creating nested form groups.
The first thing you need to add your nested group name test into your
<div formGroupName="test">
<div *ngFor="let item of fcTest | keyvalue">
<amp-check-box [formControl] = form.controls[item.key] ></amp-check-box>
</div>
</div>