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

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

Template

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

Component

isAdmin() {
    console.log(\'         


        
相关标签:
3条回答
  • 2021-01-21 04:02

    after finding this why *ngIf in angular 2 always is executing when use function?

    i resolved the problem by

    component

    ngOnInit() {
        this.is_admin();
    }
    is_admin() {
        this.isAdmin = this.bcAuthService.isAdmin();
    }
    

    html

    <pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>
    
    0 讨论(0)
  • 2021-01-21 04:04

    Now you don't have method(member instead) and it's not spamming "isAdmin: true" but it's not means that problem is resolved.

    You can be interested in changeDetection of the component and ChangeDetectorRef to actually tell angular when isAdmin is changed to update template(detectChanges).

    0 讨论(0)
  • 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

    <pre *ngIf="isAdmin">{{email|json}} - {{user|json}}</pre>
    

    Component

    export class MyComponent implements OnInit {
    
        isAdmin: boolean;
    
        ngOnInit() {
            this.isAdmin = this.bcAuthService.isAdmin();
            console.log('isAdmin: ', this.isAdmin);
        }
    }
    
    0 讨论(0)
提交回复
热议问题