我有一个包含mat-list-item
的组件,单击该组件将在复选框处于选中状态,不确定状态和未选中状态(按此顺序)之间切换状态。每个列表项都有一个数字值,该值在选中时也会加到总数上,在不确定时会从总数中减去(在此处显示为属性mitigated
),而在未选中时再次具有零值。
我使UI看起来和与click
绑定的mat-list-item
事件一起正常工作。单击列表项后,该复选框显示为选中状态。第二次单击,将应用样式,因此文本上会出现删除线,并且复选框处于indeterminate
状态。第三次单击,它将重置为未选中状态。数学也可以正确处理这种行为。
但是,当我单击复选框本身而不是列表项时,即使单击console.log
语句后,该复选框也不会显示为选中状态。每次单击都会添加列表项的数值,并且UI不会反映任何更改。我不知道为什么会这样。
我可以将事件仅绑定到复选框,但是我希望用户能够选择整个列表项以便于使用。
组件:
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { Risk } from './risk.model';
import { MatCheckboxChange, MatCheckbox } from '@angular/material';
@Component({
selector: 'app-risk',
templateUrl: './risk.component.html',
styleUrls: ['./risk.component.css']
})
export class RiskComponent {
@Input('risk') risk: Risk;
@Output() riskSelected = new EventEmitter<number>();
mitigated: boolean;
countScore: boolean;
constructor() { }
onSelect(c: MatCheckbox) {
this.mitigated = c.checked && !this.mitigated;
c.checked = ((c.checked && this.mitigated) || !c.checked);
console.log('Checked: ', c.checked); // logs true, not rendered in browser
this.countScore = c.checked && !this.mitigated;
this.changeScore(c);
}
private changeScore(c: MatCheckbox): void {
let changeValue: number;
if (!this.mitigated) {
changeValue = c.checked ? this.risk.score : 0;
} else {
changeValue = -this.risk.score;
}
this.riskSelected.emit(changeValue);
}
}
模板:
<mat-list-item fxLayout="row"
fxLayoutAlign="space-between center"
class="risk-list-item"
[class.mitigated]="mitigated"
(click)="onSelect(c)">
<div fxLayoutAlign="start center" fxFlex>
<p>
<span matBadge="{{ risk.requiresApproval ? 'AR' : ''}}"
matBadgeColor="accent" matBadgePosition="before" matBadgeOverlap="false">
{{ risk.description }}
</span>
</p>
</div>
<div fxLayout fxLayoutAlign="end center" fxFlex>
<mat-chip-list disabled="true">
<mat-chip color="primary">{{ risk.score }}</mat-chip>
</mat-chip-list>
<mat-checkbox #c color="primary" [indeterminate]="mitigated">
</mat-checkbox>
</div>
</mat-list-item>
<!-- MITIGATION NOTES -->
<div *ngIf="mitigated">
<mat-form-field>
<textarea matInput placeholder="Mitigation Note:"></textarea>
</mat-form-field>
</div>