Why can't we use [(ngModel)] and value in same input tag in angular 6

倖福魔咒の 提交于 2019-12-13 17:50:19

问题


My html tag is:

<input matInput placeholder="Vehicle Number" name="vehicleNo" [(ngModel)]="vehicleNo" value="vehicle.vehicleNo" >

I need to automatically fill the input field and if i enter new thing it need to access in component.ts file.


回答1:


In angular if you are using ngModel to bind data then you don't need to use value attribute, it will automatically bind the data.

//in ts file

export className extends OnInit{
    vehicle: any;

    ngOnInit(){

       this.serviceName.functionName().subscribe(
           data=>{
               this.vehicle=data;
           }error=>{
               //whatever logic you want to place
          }
      );
   }
}

//in html file

<input matInput placeholder="Vehicle Number" name="vehicleNo" [(ngModel)]="vehicle.vehicleNo">

// if you are defining it this way vehicleObj = { vehicleNo:this.vehicleNo }

then html file should be

<input matInput placeholder="Vehicle Number" name="vehicleNo" [(ngModel)]="vehicleObj .vehicleNo">



回答2:


this expression will not evaluate as javascript expression value="vehicle.vehicle No" this how you do property binding [value]="vehicle.vehicle No"

just set vehicleNo to vehicle.vehicleNo and the input will updated you don't need to do't by yourself this what ngModel made for .



来源:https://stackoverflow.com/questions/52699583/why-cant-we-use-ngmodel-and-value-in-same-input-tag-in-angular-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!