Home > Mobile >  how to dynamically create element with ngModel attribute using ionic?
how to dynamically create element with ngModel attribute using ionic?

Time:12-07

I'm trying to create ion-input element dynamically when user clicks on " ".Then I want to insert all values of inputs to an array. I created the inputs but I can's assign [(ngModel)] attribute to new elements. How can I do that? This is the method that creates new element:

newElement() {
    const item = document.createElement('ion-item');
    const input = document.createElement('ion-input');
    input.placeholder = 'شماره سریال';
    input.type = 'text';
    input.required = true;
    input.name = 'serialNumbers';
    input.className = 'input inputSerial';
    input.ngModel='serialNumbers';
    const div = document.getElementById('newElements');
    console.log(item);
    item.appendChild(input);
    div.appendChild(item);
  }

This is the default input when the page is loaded at first:

  <ion-item>
  <ion-input
    type="text"
    expand="block"
    placeholder="شماره سریال"
    required
    name="serialNumbers"
    [(ngModel)]="serialNumbers"
  ></ion-input>

the serialNumbers array only accepts the value of the default input

CodePudding user response:

You need to use angular templating for this. Directly manipulating the DOM is not recommended with angular. Use structural directives instead.

In your component class, have an array of inputs

serialNumbers: any = [];

In the component,

<ion-item *ngFor="let serialNumber of serialNumbers;">
  <ion-input
    type="text"
    expand="block"
    placeholder="شماره سریال"
    required
    name="serialNumbers"
    [(ngModel)]="serialNumber"
  ></ion-input>

In your newElement()

newElement(){
    this.serialNumbers.push('');//default value.
}
  • Related