using a function in *ngIf runs several times instead of once

前端 未结 3 816
野性不改
野性不改 2021-01-21 03:48

Template

{{email|json}} - {{user|json}}

Component

isAdmin() {
    console.log(\'         


        
3条回答
  •  感情败类
    2021-01-21 04:16

    Template methods will almost always be called multiple times. The same is true for *ngFor that it is iterated over multiple times. If you have something that executes an expensive call then you should cache the result and return that either in the method or use ngOnInit to retrieve/calculate the values and set them in your component.

    Template code

    {{email|json}} - {{user|json}}

    Component

    export class MyComponent implements OnInit {
    
        isAdmin: boolean;
    
        ngOnInit() {
            this.isAdmin = this.bcAuthService.isAdmin();
            console.log('isAdmin: ', this.isAdmin);
        }
    }
    

提交回复
热议问题