Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

export class InputForm {
  mapA: {};
  listA: ListA[] = [];
}

export class ListA {
    input1 : String
    input2 : number
}

I need to show it on UI in such a way that input1, input2 and key, value for map of criteria is visible as the input field. The user fills all 4 input fields and clicks on the add button.

Then again same input fields should be editable for the user for the second input. This way he can build list and map and when he clicks on submit button array and map should have all the values filled before.

*ngFor doesn't work because the initial list is empty.

like image 472
user1298426 Avatar asked Feb 04 '19 18:02

user1298426


People also ask

How do I create a dynamic form in HTML?

Approach 1: Use document. createElement() to create the new elements and use setAttribute() method to set the attributes of elements. Append these elements to the <form> element by appendChild() method. Finally append the <form> element to the <body> element of the document.


1 Answers

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>
like image 64
Faruq Avatar answered Oct 19 '22 06:10

Faruq