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'
})
exportclassOrderFormComponentimplementsOnInit{
  orderForm: FormGroup;
  items: FormArray;

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

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

  addItem(): void {
    this.items = this.orderForm.get('items') asFormArray;
    this.items.push(this.createItem());
  }
}
<!-- order-form.component.html --><divformArrayName="items"
  *ngFor="let item of orderForm.get('items').controls; let i = index;"><div [formGroupName]="i"><inputformControlName="name"placeholder="Item name"><inputformControlName="description"placeholder="Item description"><inputformControlName="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"