Angular 2+ one-time binding

前端 未结 6 1925
故里飘歌
故里飘歌 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:18

    Currently, you cannot do one time binding with Angular 2. However, you can know when your binding changes and reset your inputs.

    Angular 2 provides OnChanges lifecycle hook for the same. You need to implement OnChanges interface to get the changes.

    See the code example below where, I am storing the data-bound property in a private variable when OnInit is called.

    export class Footer implements OnInit, OnChanges {
      @Input() public name: string;
      private privname: string;
    
      constructor() { }
    
      ngOnInit() {
        this.privname = this.name;
      }
    
    
      ngOnChanges(changes: { [key: string]: SimpleChange }): void {
        if (!changes["name"].isFirstChange()) {
            this.name = this.privname;
        }
      }
    }
    

    Later when other changes occur, I am setting the value to its old value on subsequent changes.

    This mechanism works like One-time binding.

    Alternate solutions: You could also use a setter function to capture the changes.

提交回复
热议问题