saoriri備忘録

tech とか コードについてとか色々

angular material の mat-button-toggle を使ってみる。

内容

angular material に装備されているmat-button-toggle を使用して、
トグルボタンを設定してみる。
調べてみたのですが、情報が比較的少なかったのでメモ。

// angularmaterial の toggleボタンモジュールをimportする
import {
   MatButtonToggleModule
} from '@angular/material';

@NgModule({
imports: [
    MatButtonToggleModule,
],  // 省略
})
<mat-button-toggle-group class="selectAll" #group=matButtonToggleGroup name="fontStyle" aria-label="Font Style">
    <mat-button-toggle value="select" (click)="imageSelectAll(group.value)">全選択</mat-button-toggle>
    <mat-button-toggle value="deselect" (click)="imageSelectAll(group.value)">解除</mat-button-toggle>
</mat-button-toggle-group>
// toggleボタンが押された時
imageSelectAll(value: string): void {
    const b = value === 'select';
    this.imageSelects.forEach( i => i.checked = b );
}

mat-button-toggle-group#group を設定。
そうすると、mat-button-togglevalueが有効になり、
clickなどアクションした時に、group.valueとして値を持っていく事ができます。


スタイル変更で詰まった...

angular material のデフォルトデザインから自分好みにスタイルを変えようと思いましたが、
なんだかうまいことスタイルがあたってくれない。泣
.mat-button-toggle-button と直接css指定してもダメ。泣

コンポーネントの階層が違うことが原因でした。
解決策としてng:deepを使用する事で解決。

.mat-button-toggle-group {
    margin-right: 30px;

    & ::ng-deep {
        .mat-button-toggle-label-content {
            line-height: 32px;
        }
        .mat-button-toggle-button {
            padding: 3px;
        }
        .mat-button-toggle-checked {
            background-color: #CCCCCC;
            color: white;
        }
    }
}

参考サイト

Angular Material