从app.component.html
中的表单中获取值 <input type="number" class="form-control" [(ngModel)]="value" />
<!-- <p><button (click)="submit()" class="btn btn-warning btn-sm">Submit</button></p> -->
<p>value: {{ value }}</p>
<p>newvalue: {{ newvalue }}</p>
然后在app.component.ts中我只想应用向此值添加2的逻辑,将其传递给newvalue然后使用插值{{newvalue}}在app.component.html
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
value: number = null;
newvalue: number = null;
constructor(){
// this.fun();
}
ngOnInit(){
// this.fun();
}
// submit(){
// console.log(this.value);
// }
fun(){
console.log('newvalue: ' + this.newvalue);
console.log('value: ' + this.value);
this.newvalue = this.value + 2;
console.log('after->newvalue: ' + this.newvalue);
console.log('after->value: ' + this.value);
}
}
我尝试了很多东西,但我应该放在哪里
this.newvalue = this.value + 2;
这样,只要inout改变,值就会更新?
由于
答案 0 :(得分:2)
您可以使用ngModelChange
事件来完成此操作
<input type="number" class="form-control" [(ngModel)]="value" (ngModelChange)="fun()"/>
答案 1 :(得分:1)
您可以直接使用值变量,如下所示
<input type="number" class="form-control" [(ngModel)]="value" />
<p>{{ value*2 }}</p>
或使用ngModelChange
<input type="number" class="form-control" [(ngModel)]="value" (ngModelChange)="fun()"/>
<p>{{ newValue }}</p>