Angular のngClass ディレクティブの使い方
Angular ではstyle.~やclass.~というクラスバインディングやスタイルバインディングがありますが、ngClass を使うことで同様のことが可能になります。
着脱(スタイルの適用オンオフ)が可能になります。
クラスバインディングやスタイルバインディングについては「Angularのデータバインディングという仕組み」を参照ください。
ngClass ディレクティブは、複数のクラス属性のオンオフを切り替えたい場合はngClass ディレクティブを使用すべきです。
[ngClass]="{'class属性1': true,'class属性2': false}"
というように記述します。
app.component.ts
import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` <table border="1"> <tr *ngFor="let tmp of List;let i = index" (click)="onColor(i)" [ngClass]="{'aaa': isColor[i]}"> <!-- ここ --> <td>{{tmp.name}}</td> </tr> </table> `, styles: [` tr.aaa{background-color: blue;} `] }) export class AppComponent { isColor: boolean[] = [false]; List = [{'name':'Takahashi'},{'name':'Maruyama'},{'name':'Okuyama'}]; onColor(i:number) { for(let j = 0; j < this.List.length; j++) { this.isColor[j] = false;// 全行をいったんfalseにする } this.isColor[i] = true;// クリックした行のみtrueにする } }
詳細は「AngularとTypeScriptでSPAを作成する」を参照ください。
![高橋](https://i0.wp.com/confrage.jp/wp-content/uploads/2018/08/aaaaaaaaa-1.jpg?resize=100%2C100&ssl=1)
KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^
コメント