Issues with the ngModel data binding functionality

I'm currently working on the Tour of Heroes project and facing an issue with ngModel. It seems like hero.name is not being updated, or maybe it's just not reflecting in the view. Despite typing into the input field, the displayed name remains as Windstorm.

I would appreciate any guidance on what might be going wrong here.

heroes.component.html

<h2>{{ hero.name | uppercase }}</h2>
<div><span>id: </span>{{ hero.id }}</div>
<div>
  <label>name
    <input ([ngModel])="hero.name" placeholder="name">
  </label>
</div>

heroes.component.ts

import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';

@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
  hero: Hero = {
    id: 1,
    name: 'Windstorm'
  };
  constructor() { }

  ngOnInit() {
  }

}

hero.ts

export class Hero {
  id: number;
  name: string;
}

Answer №1

[(ngModel)] is the correct notation instead of ([ngModel]). This pattern is known as the box-of-bananas method ;) ()

Answer №2

To get started, navigate to the AppModule (app.module.ts) and ensure you are importing the FormsModule symbol from the @angular/forms library.

import { FormsModule } from '@angular/forms'; // <-- NgModel resides here

Next, include FormsModule in the imports array of the @NgModule metadata. This array holds a collection of external modules required by the application.

imports: [
  BrowserModule,
  FormsModule
],

Once you refresh the browser, your app should be back on track. Try modifying the hero's name and witness the instant updates right above the text box.


source: Angular documentation

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

Exploring the process of linking a C# REST API to an Ionic 2 mobile application

I am completely lost on how to connect an asp.net web api with my ionic 2 mobile app. Any help or advice on resolving this problem would be greatly valued! ...

Automatically convert TypeScript packages from another workspace in Turborepo with transpilation

I have set up a Turborepo-based monorepo with my primary TypeScript application named @myscope/tsapp. This application utilizes another TypeScript package within the same repository called @myscope/tspackage. For reference, you can view the example reposit ...

What is the process for incorporating personalized variables into the Material Ui Theme?

In the process of developing a react app with TypeScript and Material UI, I encountered an issue while attempting to define custom types for my themes. The error message I received is as follows: TS2322: Type '{ mode: "dark"; background: { default: s ...

Angular 5 - Reverting back to the previous state

In my Angular web application, I encounter a scenario where I need to navigate back to the previous state. Let's say I am currently on a page at http://localhost/someURL. On this particular page, users have the ability to search for items and see the ...

Executing asynchronous functions in Angular 2

In my Angular demo.ts file, I have included two functions fetchTables() and fetchAllTables() inside the constructor of a class. Both functions make API calls. However, I am facing an issue where one of the calls fails consistently. Sometimes fetchTables() ...

Step-by-step guide to retrieving the value of a duplicate input field with identical IDs in Angular4

This is the form I am working on: <button (click)="M_add()">Add</button> <tbody id="_tbody"> </tbody> Whenever the add button is clicked, it triggers the creation of an input field. let tbody = document.getElementById("_tbody"); ...

What is the best way to retrieve the name of a static method within a class?

In my code, I am logging multiple messages in a static method and I want to use the method name as context. However, I do not want to create a separate variable called `context` and assign the function/method name to it. I would like to be able to access ...

Steps for eliminating a selection in the dropdown list:

I am dealing with a situation in which my select element gets new options added based on a specific input value. However, each time the value is changed, more options are appended to the select element instead of replacing the old ones. How can I remove th ...

Passing back function results in an IONIC application

Currently, I am studying IONIC 5 and working with the native geolocation feature to fetch latitude and longitude coordinates. My goal is to retrieve these coordinates and then send them to a server via a form. geolocate() { this.geolocation.ge ...

The issue of excessive recursion in Typescript

Currently, I am in the process of learning Typescript while working on some exercises. While attempting to solve a particular problem, I encountered an error related to excessive recursion. This issue arises even though I created wrapper functions. About ...

What is the method for utilizing Tuple elements as keys in a Mapped Type or template literal within typescript?

Is there a specific way to correctly type the following function in TypeScript? Assuming we have a function createMap() that requires: a prefix (e.g. foo) and a tuple of suffixes (e.g. ['a', 'b', 'c']) If we call createMap(& ...

Error: The StsConfigLoader provider is not found! MSAL angular

I am currently using Auth0 to manage users in my Angular application, but I want to switch to Azure Identity by utilizing @azure/msal-angular. To make this change, I removed the AuthModule from my app.module and replaced it with MsalModule. However, I enco ...

Angular successfully compiled without any issues despite the explicit cast of a number into a string variable

As I delve into the initial concepts of Angular, I have come across a puzzling situation. Here is the code snippet: import { Component } from '@angular/core'; @Component({ selector: 'sandbox', template: ` <h1>Hello {{ nam ...

New post: "Exploring the latest features in Angular

Looking for help with integrating Angular and SpringREST to fetch data from the backend? Here's my situation: I need to retrieve a JSON string from the backend using a POST request, send it to my site's hosted link, and display it on the user int ...

Issue with Typescript Application not navigating into the node_modules directory

After attempting to load the app from the root directory of our server, it became clear that this was not a practical solution due to the way our application uses pretty URLs. For instance, trying to access a page with a URL like http://www.website.com/mod ...

What is the official name of the key type for the Built-in Object?

There was a built-in type that I used in the past which represented the union of all possible object keys. It was named objectKey or something similar. Here is an example: type objectKey = string | number | symbol Unfortunately, I am drawing a blank on t ...

The error message "NullInjectorError: No provider for HTTP!" is generated by the ionic-native/http module

Currently working with ionic 3.2 and angular. To install the HTTP module (https://ionicframework.com/docs/native/http/), I used the following commands: ionic cordova plugin add cordova-plugin-advanced-http npm install --save @ionic-native/http In my scri ...

What causes a compilation error to occur when a mapped type is invoked inside a class?

Below is a code snippet for review. An error occurs when calling the get method within the class, but works fine when called outside. Any thoughts on why? type DefinedKeys<T> = keyof { [K in keyof T as undefined extends T[K] ? never : K]: K } cla ...

Customize the form using a custom component in react-hook-form: setting a default value

I have been learning ReactJS + TypeScript for 3 months now. Recently, I have a question about using react-hook-form (v7) to edit a form. I want to integrate my custom component into the form and I managed to do it on my own! Here is a snippet of my form p ...

What steps should I take to import a module with type definitions? (receiving error TS2656: ...not a module)

I am currently working on enhancing the type definitions for a simple npm module called emitter20. The source code of this module spans 20 lines and looks like this: module.exports = function() { var subscribers = [] return { on: function (eventNa ...