When working with the first case (check out the DEMO link), patchValue() function can easily manipulate the select drop-down menu in a reactive FormGroup(), where only FormControl() is used. However, in the second case, I need to achieve the same functionality of updating the selected value directly when the user adds input. This time, I have to set the value using patchValue() inside FormArray(), which is currently not working as expected. How can I make it work within FormArray()?
FIRST CASE
app.component.ts
export class AppComponent {
entityInfoForm: FormGroup;
items = ['Mobile', 'Home', 'School'];
constructor() {
this.entityInfoForm = new FormGroup({
name: new FormControl(""),
control: new FormControl("")
});
}
addCustom(v: string) {
this.items.push(v);
this.entityInfoForm.patchValue({control: this.items[this.items.length - 1]});
}
onSubmit() {
console.log(this.entityInfoForm);
}
}
app.component.html
<form role="form" [formGroup]="entityInfoForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="usr">Name</label>
<input type="text" class="form-control" id="name" formControlName="name">
</div>
<div class="form-group">
<select formControlName="control">
<option *ngFor="let item of items" [ngValue]="item">{{item}}</option>
</select>
</div>
<button type="submit">Submit Form</button>
</form>
<input type="text" #custom>
<button (click)="addCustom(custom.value)">Add</button>
SECOND CASE Note: Here we use Dynamic FormArray, multiple options can be added in this case.
app.component.ts
export class AppComponent {
entityInfoForm: FormGroup;
items = ['Mobile', 'Home', 'School'];
constructor() {
this.entityInfoForm = new FormGroup({
name: new FormControl(""),
contact: new FormArray([
new FormGroup({
type: new FormControl(''),
contact: new FormControl('')
})
])
});
}
addCustom(v: string) {
this.items.push(v);
this.entityInfoForm.patchValue({type: this.items[this.items.length - 1]});
}
onSubmit() {
console.log(this.entityInfoForm);
}
}
app.component.html
Name <div>
<select class="form-control formControlName="type">
<option *ngFor="let item of items" [ngValue]="item">{{item}}</option>
</select>
</div>
</div>
</form>
<input type="text" #custom>
<button (click)="addCustom(custom.value)">Add</button>