gpt4 book ai didi

Angular 5 : calling method from html

转载 作者:行者123 更新时间:2023-12-05 04:06:13 25 4
gpt4 key购买 nike

我不明白为什么它不起作用。

我试图通过从 html 调用方法来显示基于条件的登录/注销链接。在控制台中,我可以看到它正在返回“true”,但它永远不会将链接更改为“注销”。屏幕上总是“登录”

<ul class="nav navbar-nav navbar-right">
<li class="nav-item dropdown" [hidden]="!authenticated()">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-user" aria-hidden="true"></i> Welcome, {{user}}!
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="nav-link dropdown-item" (click)="logout()">Logout</a>
</div>
</li>
<li class="nav-item dropdown" [hidden]="authenticated()">
<a routerLinkActive="active" routerLink="/login">Login</a>
</li>
</ul>

组件.ts

authenticated() {
console.log(localStorage.getItem('authenticated'));
if(localStorage.getItem('authenticated') === 'true') {
console.log("YES");
return true;
} else {
console.log("NO");
return false;
}
}

点击登录链接之前 enter image description here

点击登录后 enter image description here

输入正确的用户名/密码后(她可以在控制台中看到它返回 true) enter image description here

最佳答案

首先,您不应该使用 *ngIf 指令调用函数,因为它会在每次更改检测时运行。这会导致性能开销。使用变量或将您的方法转换为 getter 属性,例如

get authenticated(): boolean {
return localStorage.getItem('authenticated') === true;
}

其次,使用*ngIf代替[hidden]:

<ul class="nav navbar-nav navbar-right">
<li class="nav-item dropdown" *ngIf="authenticated">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i class="fa fa-user" aria-hidden="true"></i> Welcome, {{user}}!
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
<a class="nav-link dropdown-item" (click)="logout()">Logout</a>
</div>
</li>
<li class="nav-item dropdown" *ngIf="!authenticated">
<a routerLinkActive="active" routerLink="/login">Login</a>
</li>
</ul>

关于 Angular 5 : calling method from html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50105639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com