问题
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