如何使用Angular [ngClass]从json文件绑定类名

问题描述 投票:1回答:1

我有一个json文件包含这样的图标对象:

"icons" : {
        "logo" : "fa fa-caret-down",
        "search" : "fas fa-search",
        "bell" : "far fa-bell"
    }

在我的component.ts中,我能够像这样使用服务成功获取此图标对象:

navIcons: object;
   getNavIcons(): void {
    this.navbarService.getNavIcons()
    .subscribe(navIcons => {
      this.navIcons = navIcons;
      console.log(this.navIcons)
    //   icons : {
    //     logo : "fa fa-caret-down",
    //     search : "fas fa-search",
    //     bell : "far fa-bell"
    // }
    });
  }

如何在component.html模板中绑定thoes类?我试过这样的:

 <i id="logo" [ngClass]="['navIcons.logo']" class="nav-icon"></i>

但它失败了。我还有另一个类:nav-icon需要添加到此徽标中吗?先谢谢你!

angular ng-class
1个回答
1
投票

试试这个ngClass语法:

[ngClass]="navIcons?.logo"

由于navIcons最初是undefined,因此在尝试访问?.属性时,请使用安全导航操作符logo来防止异常。

© www.soinside.com 2019 - 2024. All rights reserved.