为什么*ngIf in angular 2总是在使用功能时执行?

Ali*_*ade 3 javascript typescript angular

我正在尝试使用angular 2创建一个应用程序,并在我的应用程序中有一个auth服务,我的html模板是这样的:

 <header>
    <div *ngIf="isLogin()"><a href="">profile</a></div>
    <div *ngIf="!isLogin()"><a href="">register</a></div>
    <div *ngIf="!isLogin()"><a href="">signin</a></div>
    </header>

**and this is my class :** 

@Component({
    selector: 'main-menu',
    templateUrl: '/client/tmpl/menu.html',
    directives: [ROUTER_DIRECTIVES]
})
export class Menu extends Ext {

    public items: any;

    constructor(private _util: UtilService, private _user: UserService) {
        super();


    }

    public isLogin() {

        console.log("test");  <==== my problem is here
        return this._user.authorized();

    }


}
Run Code Online (Sandbox Code Playgroud)

总是我的功能正在执行!(在我的身份验证服务中,我还有其他功能,他们也在运行)!这是为了使用*ngif内的功能?? !!! 我担心我的资源,我想知道它的问题与否?

Gün*_*uer 17

每次运行Angulars更改检测时,它都会评估所有绑定,因此会调用您的函数来检查视图是否需要更新.

不鼓励使用绑定中的函数.将值分配给组件类的属性并将其绑定到此属性,或者使用observables和| async管道向Angular通知已更改的值.

另一个选项是使用ChangeDetectionStrategy.OnPush只有在输入值发生变化时才运行角度变化检测的地方.