[英]Angular changing HTML if a user is logged in
So I am trying to use angular over JQuery which is a bit of a mind bender. 因此,我尝试在JQuery上使用angular,这有点麻烦。
In my app I want to change text according to a users logged in state. 在我的应用程序中,我想根据用户登录状态更改文本。 If he is logged in, I want to show: My Account, and if no one is logged in I want to show: Login / Register. 如果他已登录,我要显示:我的帐户,如果没有人登录,我要显示:登录/注册。
Easy to do in Jquery, not quite sure the best method for NG. 在Jquery中很容易做到,不太清楚NG的最佳方法。
HTML HTML
<li>
<a (click)="openLoginForm()">
<i class="fa fa-lock"></i> Login / Register</a>
<i class="fa fa-lock"></i> My Account</a>
</li>
What I would like to do is check a variable: loggedIn, if true it shows "My Account", if false it shows "Login / Register". 我想做的是检查一个变量:loginIn,如果为true,则显示“我的帐户”,如果为false,则显示“登录/注册”。
I am not 100% clear how to do this via Angular2... 我不是100%清楚如何通过Angular2执行此操作...
Something like this, set isLogged when user logs on your component: 这样,在用户登录组件时将isLogged设置为:
<a (click)="openLoginForm()">
<i class="fa fa-lock"></i> {{ isLogged ? "My Account" : "Login / Register" }}
</a>
This is only working as simple binding, it will not detect change so you could do somthing like this: 这仅用作简单绑定,它无法检测到更改,因此您可以执行以下操作:
<a (click)="openLoginForm()">
<i class="fa fa-lock"></i> {{ isLoggedTittle }}
</a>
and in component set the title: 并在组件中设置标题:
isLoggedTittle = logged ? "My Account" : "Login / Register";
Freshbm's answer is the better solution but i wanted to clarify what happens in {{ isLogged ? "My Account" : "Login / Register" }}
Freshbm的答案是更好的解决方案,但我想弄清楚{{ isLogged ? "My Account" : "Login / Register" }}
{{ isLogged ? "My Account" : "Login / Register" }}
isLogged
is usually a boolean of true or false but can be a value isLogged
通常是true或false的布尔值,但可以是一个值
?
is a check 是支票
"My Account"
if the boolean is true or the value is valid 如果布尔值为true或值有效,则为"My Account"
:
means if false, undefined or null, do this :
表示是否为false,undefined或null
"Login / Register"
if the boolean is false or the value is null or undefined 如果布尔值为false或值为null或未定义,则"Login / Register"
In your situation the ideal solution is to use ngIf
: 在您的情况下,理想的解决方案是使用ngIf
:
<li>
<a (click)="openLoginForm()" *ngIf="!loggedIn">
<i class="fa fa-lock"></i> Login / Register</a>
<a (click)="openMyAccountForm()" *ngIf="loggedIn">
<i class="fa fa-lock"></i> My Account</a>
</li>
This will show the My Account section if loggedIn
is true, and Login/Register if false. 如果loggedIn
为true,则将显示“我的帐户”部分;如果为false,则将显示“登录/注册”。
By using two different anchor tags entirely you can completely change how each one behaves, what icon is inside them etc. 通过完全使用两个不同的锚标记,您可以完全更改每个锚的行为方式,其中的图标等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.