Angular2双向绑定和组件属性更新
问题描述:
Angular2新手在这里。Angular2双向绑定和组件属性更新
我有三个数字组件属性'a','b'和'c',其中c = a + b。 “a”和“c”在模板上使用双向绑定来输入语句。如果值在视图中更改,那么它们也会在组件中更改。但是,值“c”未更新。当“a”或“b”的值发生变化时,如何获取值“c”以更新?谢谢您的帮助。
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<input type="number" [(ngModel)]="a"/>
<input type="number" [(ngModel)]="b"/>
{{c}}
`
})
export class MyComponent {
a = 1;
b = 2;
c = this.a + this.b;
}
答
设置在打字稿类字段的值实际上只是语法糖在构造函数中设置它:
export class MyComponent {
a = 1;
b = 2;
c = this.a + this.b;
}
// is the same as
export class MyComponent {
constructor() {
this.a = 1;
this.b = 2;
this.c = this.a + this.b;
}
}
现在,应该是更加清晰,为什么这不工作 - c
的值仅在组件初始化时才会设置! Angular没有办法知道c
的值取决于a
和b
。
你可以解决这个问题通过使c
的方法:
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<input type="number" [(ngModel)]="a"/>
<input type="number" [(ngModel)]="b"/>
{{c()}}
`
})
export class MyComponent {
a = 1;
b = 2;
c() {
return this.a + this.b;
}
}
的告诫,这是那就是c
将获得每次运行变化检测发生 - 这不是一个真正的问题与功能尽管这很简单,但是您需要小心,因为这会降低您的应用速度,因此您在这样的绑定中没有做太重的事情。
也就是说,我不认为你需要c!只要做这样的事情就简单多了:
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<input type="number" [(ngModel)]="a"/>
<input type="number" [(ngModel)]="b"/>
{{a + b}} or {{a}}{{b}}
`
})
export class MyComponent {
a = 1;
b = 2;
}
非常感谢您的答复。现在一切都有意义。 – Brasso
@Brasso:很高兴我能帮忙:)当我开始的时候,这种东西首先让我感到尴尬,乍一看这不是非常直观。 –