[英]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.