为什么* ngIf in angular 2总是在使用功能时执行? [英] why *ngIf in angular 2 always is executing when use function?

查看:105
本文介绍了为什么* ngIf in angular 2总是在使用功能时执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a application with angular 2,and have a auth service in my application , my html template is somthing like this:

 <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();

    }


}

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

always my functions is executing !(in my auth service i have another fuctions that they also runing) !this is for using a function inside *ngif ??!!! im worry for my resoureces and i want know its a problem or not?

推荐答案

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

Every time Angulars change detection is run, it evaluates all bindings and therefore calls your functions to check if the view needs updating.

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

Using functions in bindings is discouraged. Either assign the value to a property of your component class and bind to this property instead, or use observables and the | async pipe to notify Angular about changed values.

另一种选择是使用 ChangeDetectionStrategy.OnPush 其中角度变化检测仅在输入值发生变化时运行。

Another option is to use ChangeDetectionStrategy.OnPush where Angular change detection is only run when an input value has changed.

这篇关于为什么* ngIf in angular 2总是在使用功能时执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆