Using Angular and TypeScript: A guide to binding an ngModel to a variable key within an object

I have an object called WeeklyDriver with various keys. My goal is to iterate over an array of objects containing WeeklyDriver instances (referred to as drivers in my code), and then loop through a specific set of keys belonging to the WeeklyDriver object:

public ovrKeys:Array<keyof WeeklyDriver> = [
    'SunOvrVal',
    'MonOvrVal',
    'TueOvrVal',
    'WedOvrVal',
    'ThuOvrVal',
    'FriOvrVal',
    'SatOvrVal'
];

Below is how I declared the drivers variable:

@Input() drivers:Array<WeeklyDriver> = [];

Please note that each key mentioned earlier holds a value of type number. However, I seem to encounter an issue when trying to bind these keys to number inputs, possibly due to not specifying their type as numbers using TypeScript.

My objective is to loop through the array of WeeklyDriver objects, and then cycle through those specified keys to bind them to number input fields:

<tr *ngFor="let driver of drivers">
  <td *ngFor="let ovrKey of ovrKeys">
    <input
      type="number"
      min="0"
      step="1"
      [(ngModel)]="driver[ovrKey]"
      placeholder="New value"
    />
  </td>
</tr>

Unfortunately, I keep encountering the following error message:

Type 'any' is not assignable to type 'never'

The error seems to be linked specifically to this line:

[(ngModel)]="driver[ovrKey]"

I attempted to resolve it by adding as keyof WeeklyDriver in the html like so:

driver[ovrKey as keyof WeeklyDriver]
, but received an error for missing closing bracket ].

I also experimented with

*ngFor="let (ovrKey as keyof WeeklyDriver) of ovrKeys"
, which led to the error
Property 'ovrKey' does not exist on type 'WeeklyDriverTableComponent'. Did you mean 'ovrKeys'?

Can someone point out what might be wrong in my approach? Any suggestions or guidance would be really appreciated. Thank you!

Answer №1

Here is the code snippet for your TypeScript file:

drivers: any[] = [{ name: "dr-1" }, { name: "dr-2" }];
public ovrKeys: Array<keyof typeof WeeklyDriver> = [
'SunOvrVal',
'MonOvrVal',
'TueOvrVal',
'WedOvrVal',
'ThuOvrVal',
'FriOvrVal',
'SatOvrVal'
];

And here is how you can use it in your HTML file:

<table>
  <tr *ngFor="let driver of drivers">
    <td>{{driver.name}}</td>
    <td *ngFor="let ovrkey of ovrKeys">
       <input type="text" [(ngModel)]="driver[ovrkey]"></td>
  </tr>
</table>

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

Utilizing the date pipe in Angular2 to format multiple dates in an array

As a newcomer to front-end development and Angular2, I am faced with the task of creating an app that displays a date range based on given fromDate and endDate values. The date range format should be flexible, accommodating cases where months or years diff ...

Using Angular 2: Pass the field of each item in *ngFor as a parameter when calling a function

I have a functional management application that displays a list of services along with some information (developed last year). Now, I want to add the functionality to show "last request" information on click. However, I encountered an issue with the code i ...

Ways to parse the data from a response received from an Axios POST request

After sending the same POST request using a cURL command, the response I receive is: {"allowed":[],"error":null} However, when I incorporate the POST request in my code and print it using either console.log("response: ", resp ...

Unable to locate module: The system was unable to find the specified module '@angular-devkit/build-angular/node_modules/@babel/runtime/helpers/esm/asyncToGenerator.js'

After encountering an error with Mat Dialog boxes close button not working on IOS devices (refer to Stack Overflow), I decided to downgrade my Angular project from version 14.0.0 to 13.0.0. I followed a solution provided in another Stack Overflow thread. H ...

Whenever I try to access my Node.js API from Heroku's live server, I encounter a CORS policy error

Whenever I try to access my Node.js API from the Angular app (running on a local setup) and host the API on Heroku's live server, I encounter the following error: CORS policy: No 'Access-Control-Allow-Origin'. Interestingly, when I host the ...

The functionality of CSS Inline Block display is not displaying inline as expected

I have the following HTML and CSS code, but I am having issues getting the dropdown to display inline. .project Type{ display: inline-block; } <form class="smart-form"> <div class="row"> <div class="col col-sm-6 col-md-2 col-lg- ...

Error: The binding element titled implicitly possesses a type of 'any'

Encountering the following issue: ERROR in src/components/Header.tsx:6:18 TS7031: Binding element 'title' implicitly has an 'any' type. 4 | 5 | 6 | const Header = ({title}) => { | ^^^^^ 7 | return( 8 | ...

Validating Forms in TypeScript

Currently in the process of learning Angular 10, but encountering a challenge I have an HTML document that validates a form group in my component. When I set a value for a textbox from my component, the value is displayed correctly, but my submit button c ...

What is the process for gaining entry to the environment files of a separate project?

I am working with two Angular projects. The first project is called Main, and I need to load environment files from the second project into Main. I understand that we can access assets/a.json in another project using HttpClient.get. Can someone please ad ...

Recently updated from Angular 9 to 14 and noticed a peculiar issue in the deployed app - all API calls seem to only reference the root or hosted URL in the request URL

After upgrading the application from angular 9 to angular 14, I encountered a network call issue. The application was successfully deployed via azure devops, but all network calls were directed to the host URL instead of the expected API endpoints. For exa ...

Combine all TypeScript enums into a single one

Looking for a way to combine two separate enums into one for easier use. export enum ActionTypes1 { ClearError = 'CLEAR_ERROR', PrependError = 'PREPEND_ERROR', } export enum ActionTypes2 { IncrementCounter = 'INCREMENT_COUNT ...

Issue with Angular2 Property Change Notification

I have a directive called app.service.ts that holds the state data of the app. I'm using this directive in other components to access and modify the app state, which is functioning correctly. However, I encounter an error when I attempt to bind a pro ...

Can you explain the usage of the syntax in Angular marked with the @ sign, such as @NgModule, @Component, and @Injectable?

Angular utilizes specific syntax for declaring modules, components, and services, as shown in the example below: @Component({ ... }) export class AppComponent However, this syntax is not commonly seen in traditional JavaScript development. It begs the ...

Angular Pipe displays values properly, but ngFor fails to render them

I am using a pipe to filter my ngFor loop with exact matches that are passed through by clicking on the filter argument. Below is the code for my pipe: transform(values: any[], criteria: string, group): any[] { if (!values) { ...

Angular 2, 4, or 5 - the powerful choices for web

As I make the shift from AngularJS to Angular, I am seeking advice from fellow developers on which version of Angular to focus on learning. I have been utilizing AngularJS 1.3.7, but realize that it is outdated with significant advancements in Angular 2 a ...

Executing a series of API calls using Rxjs in Angular that result in a null response

I encountered a situation where I needed to make sequential API calls using RxJs in Angular. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id from the ...

Ways to keep information hidden from users until they actively search for it

Currently, I have a custom filter search box that is functioning correctly. However, I want to modify it so that the data is hidden from the user until they perform a search. Can you provide any suggestions on how to achieve this? Below is the code I am u ...

Retrieve the name from the accordion that was clicked

Hey there, I have a simple accordion that is based on an API called "names". <div *ngFor="let item of showDirNames | async | filter: name; let i = index;"> <button class="accordion" (click)="toggleAccordian($event, i)&q ...

Troubleshooting Component Sharing in Ionic 4 with Angular 7

I'm attempting a common task with Angular framework - reusing the same HeaderComponent component in multiple instances through a shared module. This is how my shared.module.ts looks: import { CommonModule } from '@angular/common'; import { ...

Changing HTML tags programmatically in Angular while inheriting a template

In my project, I have a Component called DataGrid that represents a table with expandable rows. Each row can be expanded to show a child DataGrid table, which is similar to the parent DataGrid component. To simplify this setup, I created a base class DataG ...