簡體   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