Angular 2 或 4 或 5 ng-style 具有超过 2 个条件输出
Angular 2 or 4 or 5 ng-style with more than 2 conditional outputs
像 angularjs 1.x 如何为超过 2 个条件实现 ngstyle?
Angularjs 1.x:
<div ng-controller="MyCtrl">
<p ng-style="cond1 ? { color:'green' } : cond2 ? {color: 'blue'} : cond3 ? {color: 'red'} : {color: ''}">Hello World!</p>
</div>
Angular-2/4/5:
在下面的深色代码中,金色和绿色是打字稿中声明的变量。
<button class="button" id="btn_status" [ngStyle]="darked? {backgroundColor:'darked'} : gold?{backgroundColor:'gold'} : green?{backgroundColor:'green'}">
此处出现错误,
如果你想要这样的东西,你最好调用一个方法。如果可能的话,您希望避免将大量逻辑放入模板中:
<button
class="button"
id="connection_status"
[ngStyle]="colorCheck()">
然后方法returns你需要的颜色。
colorCheck() {
if (this.darked) {
return {backgroundColor: 'darked'};
}
}
甚至更好,因为它们都与您设置的 class 相同:
<button
class="button"
id="connection_status"
[style.backgroundColor]="colorCheck()">
colorCheck() {
if (this.green) {
return 'green';
}
// etc
}
你也可以这样做:
<button class="button" id="btn_status" [ngStyle]="{'backgroundColor': darked || gold || green}">
组件:
darked = null;
gold = null;
green = null;
cond1() {
if(true)
this.darked = 'black'
}
像 angularjs 1.x 如何为超过 2 个条件实现 ngstyle?
Angularjs 1.x:
<div ng-controller="MyCtrl">
<p ng-style="cond1 ? { color:'green' } : cond2 ? {color: 'blue'} : cond3 ? {color: 'red'} : {color: ''}">Hello World!</p>
</div>
Angular-2/4/5: 在下面的深色代码中,金色和绿色是打字稿中声明的变量。
<button class="button" id="btn_status" [ngStyle]="darked? {backgroundColor:'darked'} : gold?{backgroundColor:'gold'} : green?{backgroundColor:'green'}">
此处出现错误,
如果你想要这样的东西,你最好调用一个方法。如果可能的话,您希望避免将大量逻辑放入模板中:
<button
class="button"
id="connection_status"
[ngStyle]="colorCheck()">
然后方法returns你需要的颜色。
colorCheck() {
if (this.darked) {
return {backgroundColor: 'darked'};
}
}
甚至更好,因为它们都与您设置的 class 相同:
<button
class="button"
id="connection_status"
[style.backgroundColor]="colorCheck()">
colorCheck() {
if (this.green) {
return 'green';
}
// etc
}
你也可以这样做:
<button class="button" id="btn_status" [ngStyle]="{'backgroundColor': darked || gold || green}">
组件:
darked = null;
gold = null;
green = null;
cond1() {
if(true)
this.darked = 'black'
}