NgModel not working in Angular4

I am learning Angular 4 from the official official site , and I came to the conclusion that binding two-way data through ngModel . However, my application stops working as soon as I add [(ngModel)] to my component template, although FormsModule is imported in the module.ts file. The component does not load.
I am using Visual Studio Code.
This is my app.component.ts

import { Component } from '@angular/core';

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



    @Component({
      selector: 'app',
      template: `
      <h1>{{ title }}</h1>
      <h2>{{hero.name}} details!</h2>
      <div><label>Id:</label> {{hero.id}} </div>
      <div>name:<input [(ngModel)]="hero.name" type="text"></div>
      `,
      styles:[`
        .selected{
          transition: padding 0.3s;
          color: mediumseagreen;
        }
      `]
    })

    export class AppComponent {
      title = 'Tour Of Heroes';

     hero:Hero = {
       id:1,
       name:"Mr. Invisible"
     };
    }  

This is app.module.ts

import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

    import { AppComponent, Hero } from './app.component';

    @NgModule({
      declarations: [
        AppComponent,
        FormsModule
      ],
      imports: [
        BrowserModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { } 

AppComponent is not loaded and just shows

Loading...

+4
source share
4 answers
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

    import { AppComponent, Hero } from './app.component';

    @NgModule({
      declarations: [
        AppComponent

      ],
      imports: [
        BrowserModule,
        FormsModule  // forms module should be in imports not in declarations
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { } 
+10
source
// add the import in module and add FormModule in import:
import { NgModule } from '@angular/core'
 imports: [
    BrowserModule,
   // add FormModule in import
    FormsModule
]
+2
source

FormsModule, imports , form ngForm, ngModel.

ngModel :

 <input [(ngModel)]="variable" #ctrl="ngModel" >

: Angular

+1

. = > = > , .

-1
source

Source: https://habr.com/ru/post/1680273/


All Articles