如何使用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
使用<mat-slide-toggle>
时,我可以修改组件中的值:
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
已按预期更新.
但是当我使用<mat-button-toggle>
时,值不会更新.我必须添加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>
Plunker Example
这篇关于如何使用Angular Material< mat-button-toggle>绑定到模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!