Guide on creating elements dynamically with the ngModel attribute in Ionic

I am currently working on dynamically creating an ion-input element when the user clicks on the "+" sign. My goal is to then insert all the input values into an array. While I have successfully created the inputs, I am facing an issue with assigning the [(ngModel)] attribute to the new elements. How can I achieve this? This is the method used to create new elements:

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);
  }

When the page first loads, this is the default input:

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

The serialNumbers array only captures the value of the default input

Answer №1

It's important to utilize angular templating for this task. Avoid directly manipulating the DOM in angular as it is not recommended. Instead, make use of structural directives.

Within your component class, create an array to store inputs

serialNumbers: any = [];

Within the component,

<ion-item *ngFor="let serialNumber of serialNumbers;">
  <ion-input
    type="text"
    expand="block"
    placeholder="Serial Number"
    required
    name="serialNumbers"
    [(ngModel)]="serialNumber"
  ></ion-input>

In your newElement()

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a timeout error when trying to test the video element with Jest

My function extracts meta data such as width and height from a video element in the following code snippet: export async function getVideoMetadata( videoBlobUrl: string, videoElement: HTMLVideoElement, ): Promise<{ width: number; height: number }> ...

The NgRx Store encountered an error: Unable to freeze

I am currently developing a basic login application using Angular, NgRx Store, and Firebase. I have implemented a login action that is supposed to log in to Firebase and store the credentials in the store. However, it seems like there is an issue in my imp ...

What steps should I take to address the numerous errors I am encountering in Atom using the Atom linter tool?

My Atom interface is showing the following errors: {Error running gjslint}(x4) {Error running selective}(x4) Upon checking the errors section, I found the following details: [Linter] Error running selective Error: ENOENT: no such file or directory, open ...

Acknowledgment Pop-up

When using the PrimeNG table with a custom modal component that I created, I encountered an issue. The edit functionality works correctly and retrieves the correct row id, however, the delete function always returns the id of the first row. dashboard.html ...

Are you familiar with Mozilla's guide on combining strings using a delimiter in Angular2+?

I found myself in need of concatenating multiple string arguments with a specific delimiter, so after searching online, I stumbled upon a helpful guide on Mozilla's website that taught me how to achieve this using the arguments object. function myCo ...

Having trouble retrieving the "history" from props?

I am working with a React component. import * as React from 'react'; import { Component } from 'react'; import { FormControl, Button } from 'react-bootstrap'; type Props = { history: any[]; }; // Question on defining Prop ...

Modules that are imported in the AppModule will not be accessible in other modules

Suppose this represents my AppModule: @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, AppRoutingModule, MaterialModule, HomeModule ], exports: [ MaterialModule ], providers: [], bootstrap: [App ...

Can you explain the significance of tslint's message: "Warning: The 'no-use-before-declare' rule necessitates type information"?

Can someone explain the significance of tslint's "no-use-before-declare" rule warning, which states that it requires type information? I've tried researching online but still don't fully understand its implications. ...

Update the router URL without switching pages, yet still record it in the browser history

One of the features on my search page allows users to perform searches and view results. Initially, I faced a challenge in updating the router URL without navigating, but I managed to overcome this by utilizing the "Location" feature. In my ngOnInit meth ...

Exploring the syntax of typescript when using createContext

Just starting out with typescript and I have some questions. Could someone break down the syntax used in this code snippet for me? What is the significance of having two groups containing signIn, signOut, and user here? Is the first group responsible fo ...

Executing asynchronous methods in a Playwright implementation: A guide on constructor assignment

My current implementation uses a Page Object Model to handle browser specification. However, I encountered an issue where assigning a new context from the browser and then assigning it to the page does not work as expected due to the asynchronous nature of ...

Having trouble getting the header to properly sort the data retrieved from an Angular service?

I am currently working on implementing a simple table (date, weight) using Angular Material. The sorting functionality using "MatSort" is already set up and functioning well (you can view an example here). Now, I am attempting to retrieve data from an HT ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

What could be causing the itemClicked() function to malfunction intermittently in Ionic2 / Angular2?

The issue at hand One common problem experienced with Angular's (click) functionality is that it may not work properly when <div> tags are utilized. In certain situations, multiple clicks might be required. I encountered the same problem mysel ...

Getting the most out of Kendo Charts for Angular: Avoid cutting off the Line Chart by setting a maximum value

Whenever I specify a maximum value in a line chart, the point that corresponds to that value ends up being cutoff. I attempted to add a margin, but unfortunately, the margin is being applied outside of the chart area. I have thoroughly reviewed the API do ...

Exploring the world of typescript with the power of ts-check

I'm having trouble figuring out how to work with a generic function using TypeScript's new ts-check feature. /** * @type {Reducer<IPoiState, any>} */ const poi = handleActions({ [ADD_BOOKMARK_START]: (state) => { return { ...sta ...

What is the best approach to eliminate the 'false' type within a setState function in React?

Hey, I've been working on a project that involves using the useState hook and dealing with state using generics. I encountered an issue where I manipulated a fetched array within a setState function using the filter method, which resulted in returnin ...

Is there a way to implement an extra placeholder attribute with Angular4?

Currently, in a project where I am utilizing Angular Material, there is a form integrated with an autocomplete component. The functionality works as expected but I am interested in implementing placeholder text once the user focuses on the input element. ...

Error thrown due to missing property in type '{}' when using TypeScript arrow function parameter

As outlined in the documentation for interfaces in TypeScript, An interface declaration serves as an alternative way to define an object type. I'm puzzled by the error I encounter in the following code snippet. My attempt is to restrict the object ...