Angular 2+ one-time binding

前端 未结 6 1923
故里飘歌
故里飘歌 2020-12-09 14:21

In angular 1 we could do one time binding in this way: {{ ::myFunction() }}.

In angular 2 this is throwing:

EXCEPTION: Template parse er         


        
6条回答
  •  天涯浪人
    2020-12-09 15:15

    Best Practice Most of the Time: ngOnInit()

    In Angular 2+ we have ngOnInit() which will generally only run one time, exactly when the component is initialized. This is the simplest and usually best solution to the issue of one-time binding.

    Binding to a function can lead to dozens of unneeded calls to that function and slow down your app.

    Instead of {{ ::myFunction() }}, create a property on the component and set its value in ngOnInit():

    export class MyComponent implements OnInit {
      myValue: any;
    
      constructor() { }
    
      ngOnInit() {
    
        this.myValue = /* CALL FUNCTIONS OR CALCULATE VALUE HERE */
    
      }
    }
    

    And then in the template, simply use:

     {{ myValue }} 
    

    Your calculation will run just once.

提交回复
热议问题