在angular中可以通過 [ngClass]、[ngStyle]動態的設定模板元素的樣式
ts文件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
heros = ['第一個測試', '第二個測試', '第三個測試'];
attr = 'blue';
constructor() { }
ngOnInit() {
}
}
html文件
<ul *ngFor="let hero of heros;let key = index;" [ngClass]="{'blue':key==0,'red':key==1,'orange':key==2}">
<li >{{key}}----{{hero}}</li>
</ul>
<div [ngStyle]="{'color':'red'}">
我是ngStyle
</div>
<p [ngStyle]="{'color':attr}">這裏使用了定義的attr</p>
css文件
.blue{
color: blue;
}
.red{
color: red;
}
.orange{
color: orange;
}
效果: