What is the method for dynamically assigning a name to ngModel?

I have the following code snippet:

vmarray[]={'Code','Name','Place','City'}
export class VMDetail {

    lstrData1:string;
    lstrData2:string;
    lstrData3:string;
    lstrData4:string;
    lstrData5:string;
    lstrData6:string;
    lstrData7:string;   
}

vm:VMDetail


<ng-container *ngFor="let datas of vmarray;  let i = index;"> 
    <mat-form-field class="example-full-width" [ngStyle]="ngStyleMapper(datas.width)">    
        <input [(ngModel)]="vm.lstrData{{i}}"   name="vm.lstrData{{i}}"  matInput placeholder ={{datas}}  (click)="dblclick(i)">
    </mat-form-field>        
</ng-container> 

I'm trying to figure out a way to dynamically define the ngModel name. Any suggestions on how to achieve this?

Answer №1

To retrieve the object member, utilize an indexer

[(ngModel)]="vm['lstrData'+i]"

Answer №2

If you are in search of the array data structure, here is a simple solution.

You can create an additional array for values and associate each field with its value based on the array index.

@Component({
    template: `
        <pre>{{ values | json }}</pre>
        <ng-container *ngFor="let field of fields; let i = index;">
            <input [name]="'field_' + i" [(ngModel)]="values[i]" />
        </ng-container>
    `,
})
class MyComponent {

    fields = ['Code', 'Name', 'Place', 'City'];

    values: string[] = [];
}

Benefits

  • Enhanced readability and ease of maintenance (simply add new fields to the fields array for expansion)
  • No necessity to introduce another data type (such as VMDetail)

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

Issue: The creation of ComponentClass is restricted due to its absence from the testing module import

The test base for my Angular Cli 6.0.1 app is set up as follows. I am using Jasmine V2.8.0 and Karma V2.0.0 Encountering an error on line 13 that says: Error: Cannot create the component AddressLookUpDirective as it was not imported into the testing mod ...

Utilizing JSDoc for establishing an index signature on a class in ES6

When working with JSDoc, achieving the equivalent of Typescript's computed property names can be a challenge. In Typescript, you'd simply define it like this: class Test { [key: string]: whatever } This syntax allows you to access these comput ...

Having trouble locating module '@angular/http'?

In the configuration file systemjs.config.js for my Angular 2 application, I included the following entry in the map object: '@angular/http': 'https://npmcdn.com/@angular/http' While trying to import '@angular/http' at the b ...

Error encountered while trying to create a new project using Angular-

After executing ng new onepage, I encountered the following error message after waiting for a few minutes: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ec8b9e8d8f898a9980c18a9facddc2dec2df">[email  ...

Show detailed information in a table cell containing various arrays using AngularJS

After integrating d3.js into my code, I now have an array with key-value pairs. Each team is assigned a key and its corresponding cost is the value. When I check the console log, it looks like this: Console.log for key and value Rate for current month [{ ...

Dynamically divide canvas screens based on fabricjs dropdown selection

I am attempting to implement split screens in fabric js, such as 1, 2, 4, 8, and 16. The screen should split based on the selection from the dropdown menu. Check out my current code where I have successfully uploaded images. If I click on the images, th ...

Production environment experiencing issues with FCM service worker functionality

Upon testing the production build on localhost, Firebase Cloud Messaging (fcm) functions correctly. However, when attempting to run it on my AWS EC2 instance, I encountered the following error: An Unhandled Promise rejection occurred: Messaging: We are un ...

Is there a way to dynamically alter the fill color of an SVG component using props along with tailwindcss styling?

Having a bit of trouble cracking this code puzzle. I've got a logo inside a component, but can't seem to pass the className fill options correctly. This is all happening in a NextJS environment with NextUI and tailwind css. const UserLogo = (prop ...

Building TypeScript Model Classes

Greetings! As a newcomer to TypeScript with a background in both C# and JavaScript, I am on a quest to create class models resembling those found in C#. Here's my attempt so far: export class DonutChartModel { dimension: number; innerRadius: ...

In Angular2, you can dynamically show or hide previous and next buttons based on the contents of the first and last div

I need a solution to dynamically hide or show previous and next buttons based on the div tags created. Each value in a list is being used to generate individual div tags using ngFor loop in Angular 2. The list being utilized is: appUlist:string[] = ["Cal ...

Using Angular Form Builder to assign a value depending on the selected option in a dropdown menu

My approach to Angular Form Builder initialization includes a group that looks like this: contactReason: this.formBuilder.group({ description: '', source: this.sourceType() }) For the 'description' field, I hav ...

The interfaced JSON object did not return any defined value

I am working on implementing a pipe in Angular 9 that will handle the translation of my table words into different languages. To achieve this, I have set up a JSON file with key-value pairs for translation services and created corresponding interfaces for ...

Apologies: the declaration file for the VueJS application module could not be located

Hey there! I'm currently working on a VueJS application using NuxtJS. Recently, I added an image cropping library called vue-croppie to my project. Following the documentation, I imported the Vue component in the code snippet below: import VueCroppie ...

Intellisense in VSCode is failing to suggest subfolder exports

In my setup, I have a repository/module specifically designed to export TypeScript types into another project. Both of these projects are using TypeScript with ECMAScript modules. The relevant part of the tsconfig.json configuration is as follows: "ta ...

Displaying error messages from custom validators in Angular 6 reactive forms using their own data

In my application, I am working with a FormArray within a FormGroup. Each FormArray consists of multiple FormGroup instances that can be added dynamically. One of the features in my application is a Custom Validator that checks for repeated data across al ...

Angular - Resolving the issue of 'property does not exist on type' in TypeScript

Currently, I am following a video tutorial which also has a text version. Despite copying the code exactly as shown in the tutorial, I encountered the following error: Error TS2339: Property 'getEmployees' does not exist on type 'Employ ...

Retrieve values from an async function with Ionic Storage

How can I retrieve the values of a token and user id that are stored in Ionic storage? Currently, I have implemented the following: auth.service.ts getToken() { return this.storage.get(TOKEN_KEY); } getId() { this.storage.get(ID); } crud.serv ...

Obtaining a binary value in the switch component of materialize framework with Typescript

Is there a way in Typescript to assign a value of 1 when a checkbox is checked and 0 otherwise? I am working on a project that uses the materialize framework. Below is the code snippet in question: <div class='switch'> <label&g ...

Error: Trying to access the 'checked' property of an undefined variable

Currently, I am working on populating my panel with data from a web API (which is already functioning) while also allowing users to add new points to the list through the panel. This is my checkbox panel: <div class="generalCharacteristicsHover" (mo ...

How come accessing the superclass's property with a getter in TypeScript is not working as expected?

class A { protected _value:number; get value() { return this._value; } } class B extends A { set value(v:number) { this._value = v; } } var b = new B(); b.value = 2; console.log(b.value);//undefined Coding Pla ...