Search code examples
angulardata-bindingangular-ngmodel

Angular 11 Can't bind to ngModel


In app written in Angular 11 I have in html file the input and two way binding:

<input type="text" class="" id="inputName"   required minlength="3" [(ngModel)]="postModel.name">

In ts file I have:

@Component({
  selector: 'app-home',
  templateUrl: './add-client.component.html',
})
export class AddClientComponent implements OnInit {

  public postModel: any = {};
  public clientDTO: ClientDTO;
  public resultMessage: string;

  constructor(private route: ActivatedRoute, private router: Router, private clientService: ClientService) {
    this.postModel.name = '';
    this.resultMessage = '';

In app module:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

imports: [
    FormsModule,
    ReactiveFormsModule,

Binding two-way doesn't work. When I type text into input in html postModel.name still is empty. When I add {{ postModel.name }} in html and type text into input the value isn't displayed.

In console I have error:

Compiled successfully.

    Error: src/app/add-client/add-client.component.html:5:73 - error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'.

    5       <input type="text" class="" id="inputName" required minlength="3" [(ngModel)]="postModel.name" style="background-color:white;">
                                                                              ~~~~~~~~~~~~~~~~~~~~~~~~~~~~

      src/app/add-client/add-client.component.ts:11:16
        11   templateUrl: './add-client.component.html',
                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        Error occurs in the template of component AddClientComponent.

But sometimes there is no error but binding doesn't work. I have Angular 11


Solution

  • You're right, AddClientComponent was missing in app module in declarations section