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

The custom validation feature in Angular 4 is failing to function as expected

Currently, my focus is on Angular 4 where I have developed a custom validator for checking CGPA values (to ensure it is between 2.0 and 4.0). Although the predefined `Validators.required` works fine, my custom validator seems to be not triggering as expect ...

Dynamic Text Labels in Treemap Visualizations with Echarts

Is it possible to adjust the text size dynamically based on the size of a box in a treemap label? I haven't been able to find a way to do this in the documentation without hardcoding it. Click here for more information label: { fontSize: 16 ...

Tips for finding the displayRows paragraph within the MUI table pagination, nestled between the preceding and succeeding page buttons

Incorporating a Material-UI table pagination component into my React application, I am striving to position the text that indicates the current range of rows between the two action buttons (previous and next). <TablePagination ...

Is Angular File API Support Compatible with HTML5?

When checking for HTML5 File API browser support in my code: private hasHtml5FileApiSupport; constructor(@Optional() @Inject(DOCUMENT) document: Document) { const w = document.defaultView; this.hasHtml5FileApiSupport = w.File && w.FileReader & ...

Using injected services within static methods may seem tricky at first, but once you

I am exploring the integration of angularjs and typescript in my project. Currently, I am working on creating an Orm factory using typescript but have encountered some challenges. The structure of my factory class is as follows: class OrmModel implements ...

What is the best way to create a memoized function in React?

I am currently developing an application using react and typescript, and I am facing a challenge in memoizing a function. const formatData = ( data: number[], gradientFill?: CanvasGradient ): Chart.ChartData => ({ labels: ["a", ...

Limiting the defaultValue of a select to one of the values of its options in TypeScript: A guide

Is there a way to configure the Select component's properties so that the defaultValue is limited to one of the predefined options values ("au" | "nz" in this scenario)? const countryOptions = [ { value: "au", l ...

Tips on sending a jsonp request in Angular2 without relying on JSONP_CALLBACK

I am attempting to send a JSONP request to a third-party website, where the callback name remains constant, regardless of what I input in the callback= parameter. Is there a method in Angular2 to specify a custom callback name? ...

What are the steps for integrating Angular Material into an existing project?

I have recently set up an Angular 2 project. Attempting to integrate Angular Material into my existing project, I followed the steps outlined in the official documentation by running the npm command: npm install --save @angular/material @angular/cdk How ...

Is it possible to set up Injector within TestBed?

Currently, I am in the process of writing test cases for a custom ErrorHandler within Angular. In my implementation, I have included Injector as a dependency in the constructor due to the understanding that providers are initialized after ErrorHandler. The ...

Angular: Utilizing Parameters in HTTP GET Requests

I've recently started using Angular. Currently, I'm working on sending a parameter in an HTTP GET request. This is what my code looks like: for (var i = 0, len = this.recentArtists.topartists.artist.length; i < len && i < h ...

Creating dynamic Kafka topic names within a NestJS microservice

Currently in Nestjs, I have integrated Kafka as my message broker and specified the topic name like so: @MessagePattern('topic-name') async getNewRequest(@Payload() message: any): Promise<void> { // my implementation logic } I am curious ...

Navigating the world of Angular 5: Essential resources for beginners

My work requires me to learn Angular 5, although Angular 7 is currently the latest version. It seems like Angular 5 may be on its way out and online resources are becoming outdated. Can anyone suggest the best and most up-to-date resources for learning Ang ...

Material UI offers a feature that allows for the grouping and auto-completion sorting

I am currently utilizing Material UI Autocomplete along with React to create a grouped autocomplete dropdown feature. Here is the dataset: let top100Films = [ { title: "The Shawshank Redemption", genre: "thriller" }, { title: " ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

Ways to expand a TypeScript interface and make it complete

I'm striving to achieve the following: interface Partials { readonly start?: number; readonly end?: number; } interface NotPartials extends Partials /* integrate Unpartialing in some way */ { readonly somewhere: number; } In this case, NotPar ...

Error: Cannot access the 'people' property as it is undefined

Can anyone assist me with troubleshooting an issue I'm having while trying to set up a Google People API authentication service in Angular? I keep encountering the following error in the Chrome console: Uncaught (in promise): TypeError: Cannot read ...

ngx-translate is being utilized to translate content in every child component within the module

I am currently utilizing ngx-translate in my Angular 7 project. The application supports translation for two languages, English and Chinese. The project follows the structure outlined below, where A.component serves as the parent component and B.component ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

How can we retrieve URL parameters with the help of ActivatedRoute in Angular?

My current route configuration is as follows: { path: "events", component: SkeletonComponent, children: [ { path: ':id', component: ViewEventComponent } ] } The constructor of my component looks ...