首页 > 解决方案 > Angular2 *ngIf 优雅的改变值的方法

问题描述

我有个问题。我的 html 看起来像这样:

<a
    href="/admin/companies"
    mat-button
    *ngIf="currentUserRole == 'Admin'"
  >
    <mat-icon
      matBadge="A"
      >business</mat-icon
    >
    Companies</a
  >
  <a 
     href="/companies" 
     mat-button 
     *ngIf="currentUserRole == 'Employer'">
    <mat-icon
      matBadge="E"
      >business</mat-icon
    >
    Companies</a
  >

正如你所看到的,我有相同的按钮,不同的是hrefmatBadge。显示的内容取决于cuurentUserRole.

我的问题是,如何从这两个按钮中制作一个具有正确编码*ngIf条件的按钮来更改我想要的内容?可能吗?

标签: htmlangular

解决方案


试试这个例子

在 ts 中 导入 {Component} from '@angular/core';

@Component({
  selector: 'button-overview-example',
  templateUrl: 'button-overview-example.html',
  styleUrls: ['button-overview-example.css'],
})
export class ButtonOverviewExample {
  currentUserRole : string = "Admin"
  roles = [{"url":"/admin/companies","id":"Admin","bid":"A","title":"Companies"},{"url":"/companies","id":"Employer","bid":"E","title":"Employee"}]
}

在 HTML 中

<div *ngFor="let role of roles">
<a 
    [href]="role.url"
    mat-button
    *ngIf="currentUserRole == role.id"
  >
    <mat-icon
      [matBadge]="role.bid"
      >business</mat-icon
    >
    {{role.title}}</a
  >
  </div>

推荐阅读