[英]How to mark mat-checkbox as checked in Angular 7
I have used a mat-checkbox in my project. 我在项目中使用了mat-checkbox。 I tried to mark the mat-checkbox as checked by using [checked]="true" 我尝试使用[checked] =“true”将mat-checkbox标记为已选中
<div *ngFor="let dwidgets of module.widgets">
<mat-checkbox [formControl]="moduleswidgets.controls['widgets']"
[checked]="(dwidgets['selected'] == '1')?true:false"
class="example-margin" (change)="selectedWidgets($event,dwidgets['widgetsmst_pk'])">
{{ dwidgets['wm_widgetname']}}
</mat-checkbox>
in the above code dwidgets['selected'] will return 1 and so it will set the checked event as true. 在上面的代码中,dwidgets ['selected']将返回1,因此它将checked事件设置为true。 But still checkbox was not checked. 但仍未选中复选框。
Anyone help me on this? 有人帮我这个吗?
In your module.widgets
array add another filed to each entity so it has boolean which refers if this entity should be checked or not 在你的module.widgets
数组中,为每个实体添加另一个module.widgets
因此它有boolean,它指的是是否应该检查这个实体
widgets = [
{ , checked: true},
{ , checked: false},
{ , checked: false}
]
Now in your template.html
and by using [(ngModel)]
现在在您的template.html
并使用[(ngModel)]
<div *ngFor="let dwidgets of module.widgets">
<mat-checkbox [formControl]="moduleswidgets.controls['widgets']"
[(ngModel)]="dwigets.checked"
class="example-margin" (change)="selectedWidgets($event,dwidgets['widgetsmst_pk'])">
{{ dwidgets['wm_widgetname']}}
</mat-checkbox>
because you're using a formControl
the checked won't work. 因为你使用的是formControl
所以检查不起作用。
you need to update the value of the control and it will update the checkbox accordingly. 您需要更新控件的值,它将相应地更新复选框。
but there's another issue here that you're adding the same control for all the checkboxes. 但是这里有另一个问题,你要为所有复选框添加相同的控件。
so .. you either remove the formControl
and update the data yourself using the change
method, or use [(ngModel)]
. 所以..你要么删除formControl
并使用change
方法自己更新数据,要么使用[(ngModel)]
。
or you need to use form arrays 或者您需要使用表单数组
please consider reading forms in Angular to understand more. 请考虑阅读Angular中的表格以了解更多信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.