【问题标题】:Conditional (if, else) in Angular 2Angular 2中的条件(如果,否则)
【发布时间】:2016-12-15 14:35:05
【问题描述】:

我在 .NET 和 Silverlight 中工作了几年,现在我开始使用 Angular 2 和 Expressjs。 而且我怀疑即使我找不到如何在 angular 2 + Expressjs 中执行此操作,并且对客户端安全?

<% if(User.Identity.IsAuthenticated){ %>
     <b>Sign Out</b>
<% } else { %>
     <b>Sign In</b>
<% } %>

【问题讨论】:

    标签: express angular conditional


    【解决方案1】:

    如果你需要“else”,也许最好的方法是使用 NgSwitch (https://angular.io/docs/ts/latest/api/common/index/NgSwitch-directive.html)

    比如:

    <div [ngSwitch]="User?.Identity?.IsAuthenticated">
      <b *ngSwitchCase="true">Sign Out</b>
      <b *ngSwitchDefault>Sign In</b>
    </div>
    

    【讨论】:

      【解决方案2】:

      使用 Angular 4,现在可以做到这一点:

      • 同步

        假设我们已经定义了这个类变量:

        shown: boolean = true;
        

        If else 语法:

        <button (click)="shown = !shown">toggle 'shown' variable</button>
        <div *ngIf="shown; else elseBlock">If shown</div>
        <ng-template #elseBlock>else not shown</ng-template>
        

        请注意,必须使用ng-template 才能使此结构指令起作用,因此如果您有自定义组件,请将其包装在ng-template 中。下面是另一种语法,它也绑定到同一个类变量。

        If then else 语法

        <button (click)="shown = !shown">toggle 'shown' variable</button>
        <div *ngIf="shown; then primaryBlock; else secondaryBlock"></div>
        <ng-template #primaryBlock>If shown</ng-template>
        <ng-template #secondaryBlock>else not shown</ng-template>
        

      • 异步

        类:

        userObservable = new Subject<{first: string, last: string}>();
        onButtonClick() {
          this.userObservable.next({first: 'John', last: 'Smith'});
        }
        

        模板:

        <button (click)="onButtonClick()">Display User</button>
        <div *ngIf="userObservable | async as user; else loading">
          Hello {{user.last}}, {{user.first}}!
        </div>
        <ng-template #loading>Waiting for click...</ng-template>
        

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-09-10
        • 1970-01-01
        • 1970-01-01
        • 2023-03-06
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多