![](/img/trans.png)
[英]mat-checkbox does not check if condition is false (only on double click)
[英]mat-checkbox check only if condition is true
我有一個帶mat-checkbox
的用戶表列表。 單擊mat-checkbox
,僅當某個條件為真時才應選中該復選框。
在此代碼中,我試圖僅為id=2
檢查復選框。 但正如您所看到的,最初單擊2
復選框時,即使將2
添加到應檢查的元素數組,也不會檢查它。
另一方面,當單擊1,3 or 4
復選框時,將檢查它們。
component.html
<tbody>
<tr *ngFor="let user of users; let in = index">
<td>
<mat-checkbox [ngModel]="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
</td>
</tr>
</tbody>
component.ts
export class AppComponent {
users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
checked: boolean = true
constructor() { }
selected: any = [];
canbeChecked(id): boolean {
console.log("check " + id)
console.log(this.selected)
return this.selected.includes(id);
}
userSelectClick(id) {
if (!this.selected.includes(id)) {
if (id == 2)
this.selected.push(id);
console.log("select " + id)
console.log(this.selected)
}
else {
this.selected = this.selected.filter(item => item !== id)
}
}
}
工作代碼: https : //stackblitz.com/edit/mat-checkbox-conditional
我在html中使用了ngModel
上的事件綁定,還修改了ngModel
中的一些代碼。 現在只能選中ID為2的復選框。 請參閱下面的代碼
在app.component.html中
<mat-checkbox (ngModel)="canbeChecked(user.id)" (click)="userSelectClick(user.id)"></mat-checkbox>
在app.component.ts中
export class AppComponent {
users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
checked: boolean = true
constructor() { }
selected: any = [];
canbeChecked(id): boolean {
console.log(this.selected.includes(id));
return this.selected.includes(id);
}
userSelectClick(id) {
if (!this.selected.includes(id)) {
if (id == 2){
this.selected.push(id);
}
else{
return false;
}
}
else {
if(id == 2){
this.selected = [];
}
else
return false;
}
}
}
這是一個有效的鏈接
我是stackoverflow的新手。你可以嘗試更改事件。
component.ts
import { Component } from '@angular/core';
@Component({
selector: 'material-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent {
user_checked = false;
users = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
checked: boolean = false;
constructor() { }
selected: any = [];
canbeChecked(id): boolean {
console.log("check " + id)
console.log(this.selected)
return this.selected.includes(id);
}
userSelectClick(event,id) {
if (!this.selected.includes(id)) {
if (id == 2)
this.selected.push(id);
console.log("selecrted iDs " + id)
console.log(this.selected)
}
else {
this.selected = this.selected.filter(item => item !== id)
}
}
}
/**
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
component.html
復選框
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.