简体   繁体   中英

ngModel is not updating the value to component in Angular

The ngModel is not working. I'm using it with textbox.

app.component.html

<input type="text" [value]="name" [ngModel]="name">
Name is: {{name}}

app.component.ts

name = '';
  constructor() { }

  ngOnInit(): void {
    this.name = "Hello";
  }

When I change the textbox value in browser, the value is not changing in the component.But the twoway data binding is working with [(ngModel)]="name". Please help.

From ngModel description ,

If you have a one-way binding to ngModel with [] syntax, changing the domain model's value in the component class sets the value in the view. If you have a two-way binding with [()] syntax (also known as 'banana-in-a-box syntax'), the value in the UI always syncs back to the domain model in your class.

Either you can work with [(ngModel)] , the two-way binding as you mentioned,

or you need to have the (ngModelChange) event binding to update the variable with the input's value.

<input
  type="text"
  [ngModel]="name"
  (ngModelChange)="name = $event"
/>

Demo @ StackBlitz

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM