I am trying to make a specific form field in my overall form dynamic so that x amount of objects can be added to the array of that field. However, every time the page inits I get a
Error: Cannot find control with path: 'media -> '
This is my form.ts
this.cardForm = new FormGroup({
'title': new FormControl(cardTitle),
media: this._fb.array([
this.initMedia(),
]),
'links': new FormGroup({
'news': new FormControl(news),
}),
initMedia() {
return this._fb.group({
type: new FormControl(),
raw: new FormControl(),
primary: new FormControl(),
thumbs: this._fb.group({
default: new FormControl()
})
})
}
addMedia(){
const control = <FormArray>this.cardForm.controls['media'];
control.push(this._fb.control(['']));
}
removeMedia(i: number){
const control = <FormArray>this.cardForm.controls['media'];
control.removeAt(i);
}
this is my form.html:
<div class="row">
<div class="col-xs-12">
<form [formGroup]="cardForm" (ngSubmit)="onSubmit(cardForm.value)">
<div class="row">
<div class="col-xs-12">
<button
type="submit"
class="btn btn-success">
Update Card</button>
<button
type="button"
class="btn btn-danger"
(click)="onCancel()">
Cancel</button>
</div>
</div>
<div formArrayName="media">
<div class="row">
<div class="col-xs-12">
<div class="form-group">
<div *ngFor= "let media of cardForm.controls.media.controls; let i=index">
<span>Media {{i + 1}}</span>
<span *ngIf="cardForm.controls.media.controls.length > 1" (click)="removeMedia(i)"></span>
</div>
<div [formGroupName]="i">
<div>
<label>Url</label>
<md-input-container class="mdcontainer">
<input mdInput placeholder="Media Url" type="text" formControlName="raw">
</md-input-container>
</div>
</div>
</div>
</div>
</div>
</div>
And the media[] looks like this:
media: [
{
raw:'string',
primary: boolean,
type: 'string',
thumb: {
default: 'string'
{
}
]
What am I missing/doing wrong here for that error to come up? Any help/tips/suggestions would be much appreciated.
You could try the get method instead. I think it is a bit more user-friendly:
Check it out in the docs here: https://angular.io/guide/reactive-forms#inspect-formcontrol-properties
[formGroupName]="i"
should be inside of*ngFor
. In this casei
variable will have nonundefined
valuePlunker Example