Angular2 双向绑定和组件 属性 更新

Angular2 Two-way binding and component property updates

这里是 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;
    }

在 TypeScript 中设置 class 字段的值实际上只是在构造函数中设置它的语法糖:

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 的值取决于 ab

你可以通过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;
}