繁体   English   中英

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中设置类字段的值实际上只是在构造函数中设置它的语法糖:

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

暂无
暂无

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

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