简体   繁体   English

Angular mat-checkbox indeterminate 未按预期运行

[英]Angular mat-checkbox indeterminate not behaving as expected

I'm using Angular 7 and Angular Material 7.3.7, and I'm trying to create an unordered list of mat-checkbox.我正在使用 Angular 7 和 Angular Material 7.3.7,我正在尝试创建一个无序列表的 mat-checkbox。 I am experiencing inconsistent behavior, where the indeterminate is not always showing when it should.我遇到了不一致的行为,其中不确定的并不总是显示它应该何时显示。 Here is my code:这是我的代码:

HTML: HTML:

<ul>
  <li *ngFor="let persona of personas">
    <mat-checkbox [checked]="persona.checked" [indeterminate]="persona.indeterminate">
      {{ labels[persona.name] }}
    </mat-checkbox>
  </li>
</ul>

TS: TS:

// Called by event listener. Updates the data displayed by checkboxes
updateDataCallback = () => {
  // does some logic
  // updates personas object, for example:
  this.personas = [
    {name: 'persona1', checked: false, indeterminate: false},
    {name: 'persona2', checked: false, indeterminate: true},
    {name: 'persona3', checked: false, indeterminate: false},
    {name: 'persona4', checked: false, indeterminate: false},
  ]
}

The specific issue I've noticed is that when I move from this state checked: true, indeterminate: false to this state checked: false, indeterminate: true it does not change - the checkbox stays checked and does not represent the indeterminate state. The specific issue I've noticed is that when I move from this state checked: true, indeterminate: false to this state checked: false, indeterminate: true it does not change - the checkbox stays checked and does not represent the indeterminate state. I haven't found any other issues but it wouldn't surprise me if there are other similar issues.我没有发现任何其他问题,但如果还有其他类似问题,我不会感到惊讶。

Is there some other way I should be handling the checked and indeterminate logic?还有其他方法我应该处理检查和不确定的逻辑吗? This seems to work okay most of the time, but with some of the corner cases I need to find a better solution.这似乎在大多数情况下都可以正常工作,但是对于一些极端情况,我需要找到更好的解决方案。 Thanks!谢谢!

In the documentation of Angular Material , it is stated that:Angular Material的文档中指出:

check-indeterminate: Default behavior of mat-checkbox. check-indeterminate: mat-checkbox 的默认行为。 Always set indeterminate to false when user click on the mat-checkbox.当用户单击 mat-checkbox 时,始终将不确定设置为 false。 This matches the behavior of native这符合本机的行为

So, it seems after toggling on the checkbox, the indeterminate state becomes false and then we cannot see the state again unless we explicitly set it to false again.因此,似乎在切换复选框后,不确定的 state 变为 false,然后我们无法再次看到 state,除非我们再次明确将其设置为 false。 There is an example in the documentation which will provide you an idea of how to make use of indeterminate state.文档中有一个示例,它将让您了解如何使用不确定的 state。 Refer the link ( stackblitz ) to their example.参考他们的例子的链接( stackblitz )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM