angular 6 中动态更改图标

Dynamically change icon in angular 6

我正在尝试根据特定值更改 font-awesome 图标,但即使我的模型已更改,它仍保持设置为原始图标。这是我的代码

Controller

if (foo.change < 0) {
   foo.icon = "fa fa-sort-down";
} else {
  foo.icon = "fas fa-sort-up";
}

在我的HTML

<i [className]="foo.icon"></i>

有没有办法根据 modelcheck 动态更新图标?

使用 [ngClass]

<i  [ngClass]="foo.change < 0 ? 'fa fa-sort-down' : 'fas fa-sort-up'"></i>

我在网上找到this

The error is due to the fontawesome JS library wich dynamically replace the elements defined with specific classes by svg elements sharing attributes of the initial element, so you cannot use the element tag name to select it: you need to select the new svg created element by another way

所以,最简单的解决方案是:

<i *ngIf="foo.change < 0" [className]="fa fa-sort-down"></i>
<i *ngIf="foo.change >= 0" [className]="fas fa-sort-up"></i>

对于任何徘徊在这个问题上的人,解决方案是使用 angular font awesome。查看解释

我能够使用 angular 很棒的字体 link

来实现它

我知道这不是合法(干净)的技术方法,但我会在不同的 DIV 中放置两个 fa fa 图标,同时隐藏一个。而不是通过点击 JavaScript 功能隐藏 属性。取决于你的 JavaScript 技能有多高,你可以组合一些循环、计数器等并使任何事情都有效。

<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>

<div id="up">
 <button onclick="myFunction()">
  Sort <i class="fa fa-sort-up"></i>
 </button>
</div>
<div id="down" hidden>
 <button onclick="myFunction()">
  Sort <i class="fa fa-sort-down"></i>
 </button>
</div>

<script>
function myFunction(){
 var up = document.getElementById('up');
 var down = document.getElementById('down');
 
 if (down.hidden == true){
  down.hidden = false;
  up.hidden = true;
 } else {
  down.hidden = true;
  up.hidden = false;
 }
}
</script>
</body>
</html>

希望对您有所帮助:)

<i class="pi" [ngClass]="{'true-icon pi-check-circle': dataEithertrueOrFalse, 'false-icon pi-times-circle': !dataEithertrueOrFalse}"></i>

如果您想动态更改样式,您可以创建一个函数(这里我创建了一个名称为 Color 的函数,其输入是 dataEithertrueOrFalse)。

<i class="pi" [style.color]="function_Color(dataEithertrueOrFalse)" [ngClass]="{'true-icon pi-check-circle': dataEithertrueOrFalse, 'false-icon pi-times-circle': !dataEithertrueOrFalse}"></i>