Skip to content Skip to sidebar Skip to footer

How To Add Input Fields Dynamically In Angular 6

I need to add input fields to array of objects and a map which grows dynamically based on user's choice. For e.g. InputForm has a list and a map which needs to be filled by user. e

Solution 1:

Assuming you are using Angular Reactive Form, you can use a combination of *ngFor and FormArray. You can start with an empty FormArray and add dynamically using the .push() method.

Here is a good and detailed example

// order-form.component.ts:

@Component({
  selector: '...',
  templateUrl: './order-form.component.html'
})
export class OrderFormComponent implements OnInit{
  orderForm: FormGroup;
  items: FormArray;

  constructor(private formBuilder: FormBuilder) {}
  ngOnInit() {
    this.orderForm = this.formBuilder.group({
      customerName: '',
      email: '',
      items: this.formBuilder.array([ this.createItem() ])
    });
  }

  createItem(): FormGroup {
    return this.formBuilder.group({
      name: '',
      description: '',
      price: ''
    });
  }

  addItem(): void {
    this.items = this.orderForm.get('items') as FormArray;
    this.items.push(this.createItem());
  }
}
<!-- order-form.component.html -->

<div formArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;">
  <div [formGroupName]="i">
    <input formControlName="name" placeholder="Item name">
    <input formControlName="description" placeholder="Item description">
    <input formControlName="price" placeholder="Item price">
  </div>

  Chosen name: {{ orderForm.controls.items.controls[i].controls.name.value }}
</div>

Post a Comment for "How To Add Input Fields Dynamically In Angular 6"