以下是代码:
.HTML:
<input type="text" [(ngModel)]="car.name"/>
<button (click) = "save()" ></buton>
{{car.name}} // the init value is "BWM" from Ajax;
TS:
car = new Car();
ngOnInit(){
// eg: I get the car.name from here. The car.name = "BMW";
this.http.get('/data').subscribe(car => this.car = car);
}
save(){
// Here how I compare the car.name with "BMW" ?
}
class Car{
constructor(private string name){}
}
car.name 总是变化,因为我使用ngModel。我想将其与第一个值"BWM"进行比较。我正在学习角度形式.如何使用?还是使用 Rxjs?
我不能接受这个:
car2 = new Car();
save() {
this.car2 = JSON.parse(JSON.stringify(car));
if(car.name == car2.name)
console.log("the name is BWM");
}else{
console.log("the name isn't BWM");
}
我会说为此使用单独的对象:
.HTML:
...
<input type="text" [(ngModel)]="inputCarName"/>
...
TS:
car = new Car();
inputCarName: string;
ngOnInit(){
// eg: I get the car.name from here. The car.name = "BMW";
this.http.get('/data').subscribe(car => this.car = car);
}
save(){
// Here how I compare the car.name with "BMW" ?
if(inputCarName == this.car.name)
{
//...whatever
}
}
class Car{
constructor(private string name){}
}
所以如果你想将旧值与最新值进行比较,请在输入中添加一个变量,例如
[(ngModel)]="myModel" #newvalue (change)="changeEvent(newvalue.value)"
和打字稿
changeEvent(newValue) {
console.log(newValue, this.myModel);
}
希望这有帮助。 在此处查找详细的使用角度模板引用变量