does angular have the “computed property” feature like in vue.js?

前端 未结 6 1514
我在风中等你
我在风中等你 2020-12-28 12:24

I learnt Vue.js first, and now have a project in Angular 4 so I just learnt Angular. I find everything is not that different from Vue except the \"Computed Property\". In Vu

6条回答
  •  天命终不由人
    2020-12-28 12:51

    I will try to improve upon Andzej Maciusovic's hoping to obtain a canonical answer. Indeed VueJS has a feature called computed property that can be quickly shown using an example:

    
    
    
    

    Whenever the user changes input value for a or b, both product and productFunc are logging to console. If user changes c, only productFunc is called.

    Coming back to Angular, mobxjs really helps with this issue:

    1. Install it using npm install --save mobx-angular mobx
    2. Use observable and computed attributes for bound properties

    TS file

        import { observable, computed } from 'mobx-angular';
    
        @Component({
           selector: 'home',
           templateUrl: './home.component.html',
           animations: [slideInDownAnimation]
        })
        export class HomeComponent extends GenericAnimationContainer {
           @observable a: number = 2;
           @observable b: number = 3;
           @observable c: number = 4;
    
           getAB = () => {
               console.log("getAB called");
               return this.a * this.b;
           }
    
           @computed get AB() {
               console.log("AB called");
               return this.a * this.b;
           }
        }
    

    Markup

    A =

    B =

    C =

    A * B = {{ getAB() }}

    A * B (get) = {{ AB }}

    If a or b is changed, AB is called once and getAB several times. If c is changed, only getAB is called. So, this solution is more efficient even when computation must be performed.

提交回复
热议问题