![](/img/trans.png)
[英]Getting the checked value of a mat-checkbox - Angular Material
[英]angular mat-checkbox checked value
我有 ts 代碼:
import {Component} from '@angular/core';
@Component({
selector: 'checkbox-configurable-example',
templateUrl: 'checkbox-configurable-example.html',
styleUrls: ['checkbox-configurable-example.css'],
})
export class CheckboxConfigurableExample {
checked = false;
indeterminate = false;
align = 'start';
disabled = false;
items = [{selected: true, label: 'First Item'}, {selected: false, label: 'Second Item'}];
}
html 代碼:
<mat-card>
<mat-card-content>
<h2 class="example-h2">Checkbox configuration</h2>
<section class="example-section">
<mat-checkbox class="example-margin" [(ngModel)]="checked">Items</mat-checkbox>
</section>
<h2 class="example-h2">Result</h2>
<section class="example-section" *ngFor="let item of items">
<mat-checkbox class="example-margin" [(ngModel)]="checked">{{item.label}}</mat-checkbox>
</section>
</mat-card-content>
</mat-card>
css 文件:
.example-h2 {
margin: 10px;
}
.example-section {
display: flex;
align-content: center;
align-items: center;
height: 60px;
}
.example-margin {
margin: 0 10px;
}
根據代碼,我有一個 mat-checkbox 'Items' 和 2 mat-checkboxes 'First Item'、'Second Item'。 如果未選中“項目”,則必須自動取消選中“第一項”和“第二項”。 如果選中“Items”復選框,則必須選中“First Item”和“Second Item”復選框。
如何實現以下行為(除了上述條件)?
您應該創建兩個方法,例如:onCheckedItem、onCheckedResult。 在 onCheckedItem 方法中,將每個items.selected
值設置為checked
值(真或假,取決於檢查值)。 在 onCheckedResult 我們創建了一個數組來保存items.selected
值,如果這個selectedArray
包含 true,它將設置checked
的復選框值 true,否則它將為 false。 如果您有items.selected
,則需要 ngOnInit 生命周期掛鈎:最初在您的項目 object 中為true
。
import {Component, OnInit} from '@angular/core';
....
export class CheckboxConfigurableExample implements OnInit{
checked: boolean = false;
items = [
{selected: true, label: 'First Item'},
{selected: false, label: 'Second Item'}
];
ngOnInit(): void {
this.onCheckedResult();
}
onCheckedItem() {
this.items.forEach((item) => {
item.selected = this.checked
});
}
onCheckedResult() {
let selectedArray = [];
this.items.forEach((item) => {
selectedArray.push(item.selected)
});
selectedArray.includes(true) ? this.checked = true : this.checked = false;
}
}
在您的模板中,您必須在每個復選框上設置更改事件,如下所示:
<h3>Checkbox configuration</h3>
<mat-checkbox (change)="onCheckedItem()" [(ngModel)]="checked"> Item</mat-checkbox>
<h3>Results</h3>
<ng-container *ngFor="let item of items">
<mat-checkbox (change)="onCheckedResult()" [(ngModel)]="item.selected" class="chk-box">
{{ item.label }}
</mat-checkbox>
</ng-container>
干杯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.