如何使用 Angular Material <mat-button-toggle> 绑定到模型? [英] How to bind to model with Angular Material <mat-button-toggle>?
问题描述
看看这个Plunker:https://plnkr.co/edit/yu95hUrKlUh4Ttc5SwYD?p=preview
Take a look at this Plunker: https://plnkr.co/edit/yu95hUrKlUh4Ttc5SwYD?p=preview
当我使用
时,我可以修改组件中的值:
When I'm using <mat-slide-toggle>
, I am able to modify the values in my component:
<mat-slide-toggle [(ngModel)]="myFlagForSlideToggle">Toggle me!</mat-slide-toggle>
myFlagForSlideToggle
已按预期更新.
但是当我使用
时,值不会更新.我不得不添加 ngDefaultControl
才能使这个示例工作,但我不确定它有什么关系.
But when I'm using <mat-button-toggle>
, the values are not updated. I had to add ngDefaultControl
to even make this example work, but I'm not sure how it matters.
<mat-button-toggle [(ngModel)]="myFlagForButtonToggle" ngDefaultControl>Toggle me!</mat-button-toggle>
将按钮状态绑定到组件的正确方法是什么?
What is the correct way to bind a button state to the component?
推荐答案
MatButtonToggle
组件没有实现 ControlValueAccessor
因此你不能使用 ngModel代码>就可以了.
ngDefaultControl
被引入用于其他目的.
MatButtonToggle
component doesn't implement ControlValueAccessor
therefore you can't use ngModel
on it. ngDefaultControl
was introduced for other purposes.
MatButtonToggle
应该是 mat-button-toggle-group
的一部分.但是如果你想将它用作一个独立的组件并将模型绑定到它,这里有一些你可以这样做的例子:
MatButtonToggle
is supposed to be a part of mat-button-toggle-group
. But if you want to use it as a standalone component and bind model to it here is some example of how you can do it:
<mat-button-toggle
[checked]="myFlagForButtonToggle"
(change)="myFlagForButtonToggle = $event.source.checked">
Toggle me!
</mat-button-toggle>
这篇关于如何使用 Angular Material <mat-button-toggle> 绑定到模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!