I'm currently working on a project that involves dynamically adding and removing form elements. You can check out an example I’m following at this link.
In the HTML file, I encountered a warning message regarding the 'filters' identifier not being defined within the code even though it functions correctly. The selects in the form are interlinked, meaning selecting one level will automatically populate all level selects.
<table class="example-full-width" cellspacing="0" formArrayname="filters" *ngFor="let filters of eventForm.controls.filters.controls; let i=index">
<span>Address {{i + 1}}</span>
<span *ngIf="eventForm.controls.filters.controls.length > 1" (click)="removeFilters(i)">x</span>
<tr>
<td>
<md-select [(ngModel)]="filterUserOcc" [ngModelOptions]="{standalone: true}" placeholder="Occupation" (ngModelChange)="filterUserOccupation()">
<md-option [value]="null">Occupation</md-option>
<md-option *ngFor="let occupation of occupations | async" [value]="occupation.occupation">
{{ occupation.occupation }}
</md-option>
</md-select>
</td>
</tr>
<tr>
<td>
<md-select [(ngModel)]="filterUserLvl" [ngModelOptions]="{standalone: true}" placeholder="Level" (ngModelChange)="filterUserLevel()">
<md-option [value]="null">Level</md-option>
<md-option *ngFor="let level of levels | async" [value]="level.level">
{{ level.level }}
</md-option>
</md-select>
</td>
</tr>
</table>
app.module.ts
...
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
...
imports: [
...
ReactiveFormsModule,
...
],
component.ts
...
import { FormGroup, FormControl, FormArray, FormBuilder, Validators } from '@angular/forms';
...
export class NewEventComponent implements OnInit {
eventForm: FormGroup;
...
constructor(
...
private formBuilder: FormBuilder,
...
) {
...
}
ngOnInit() {
this.eventForm = this.formBuilder.group({
...
filters: this.formBuilder.array([
this.initFilters()
])
});
}
initFilters() {
return this.formBuilder.group({
level: ['', Validators.required],
occupation: ['']
});
}
addFilters() {
const control = <FormArray>this.eventForm.controls['filters'];
control.push(this.initFilters());
}
removeFilters(i: number) {
const control = <FormArray>this.eventForm.controls['filters'];
control.removeAt(i);
}