简体   繁体   English

Angular 11 三元表达式 *ngIF

[英]Angular 11 Ternary expression *ngIF

I am stuck a bit.我有点卡住了。 I am trying to write *ngIf else statement using ternary expression The goal is to write *ngIf if a user is loggedin the logo a href leads to one Url if not logged in href leads to another URL.我正在尝试使用三元表达式编写 *ngIf else 语句 目标是编写 *ngIf 如果用户已登录徽标 a href 会导致一个 Url 如果未登录 href 会导致另一个 URL。

https://stackblitz.com/edit/angular-ivy-oyyuxu?file=src%2Fapp%2Fapp.component.html https://stackblitz.com/edit/angular-ivy-oyyuxu?file=src%2Fapp%2Fapp.component.html

Thanks谢谢

You can use ternary expressions in template like this:您可以像这样在模板中使用三元表达式:

<a [href]="auth.loggedInUser ? 'http://userLogged' : 'http://userNotLogged'">

Without being sure how to implement your login, I changed your code to work:在不确定如何实现登录的情况下,我更改了您的代码以使其正常工作:

// app.component.ts 
export class AppComponent {
    name = 'Angular ' + VERSION.major;
    public auth: any = { loggedInUser: false };
}

// app.component.html
<a *ngIf="!auth.loggedInUser">
  <img id="nav-logo"
                src="https://icm.aexp-static.com/shopamex/img/global-images/Parks_3.jpg"/>
</a>

However, a simple login would look more like this:然而,一个简单的登录看起来更像这样:

import { Component } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html'
})
export class AppComponent {
  public auth: { loggedInUser: boolean };

  public constructor(protected authService: AuthService) {
    let login$: Observable<boolean> = this.authService.Login();
    let sub: Subscription = login$.subscribe((success:boolean) => {
       this.auth.loggedInUser = success;
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM