简体   繁体   English

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

[英]Angular2 Two-way binding and component property updates

Angular2 newbie here. Angular2新手在这里。

I have three numeric component properties 'a', 'b' and 'c' where c = a + b. 我有三个数字组件属性“ a”,“ b”和“ c”,其中c = a + b。 'a' and 'c' use two-way binding to input statements on the template. 'a'和'c'使用双向绑定来在模板上输入语句。 If the values are changed in the view, then they also change in the component. 如果值在视图中更改,则它们在组件中也会更改。 However, value 'c' is not updated. 但是,值“ c”不会更新。 How do I get value 'c' to update whenever the values of 'a' or 'b' are changed? 每当“ a”或“ b”的值更改时,如何获取值“ c”进行更新? Thanks for the help. 谢谢您的帮助。

    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;
    }

Setting the value of a class field in TypeScript is actually just syntax sugar for setting it in the constructor: 在TypeScript中设置类字段的值实际上只是在构造函数中设置它的语法糖:

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;
    }
}

Now it should be a lot clearer why this doesn't work - the value of c only gets set when the component is initialized! 现在应该更清楚为什么不起作用-仅在初始化组件时设置c的值! There's no way of Angular knowing that the value of c is dependent on a and b . Angular无法知道c的值取决于ab

You could get around this by making c a method: 您可以通过使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;
   }
}

The caveat to this is that is that c will get run every time change detection takes place - that's not really an issue with a function as simple as this, but you need to be careful that you're not doing anything too heavy in a binding like this, as it'll slow your app down. 需要注意的是,每次更改检测发生时c都将运行-如此简单的函数并不是真正的问题,但是您需要小心,不要在绑定中做过多的事情这样,因为它会使您的应用变慢。

That said, I don't think you need c at all! 就是说, 我认为您根本不需要c! It'd be much simpler to just do something like this: 像这样做会简单得多:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM