【发布时间】:2020-04-02 22:18:47
【问题描述】:
我现在正在学习 Angular。我正在制作一个包含一组复选框的反应式表单。我已经使用 Angular Material 创建了这些复选框。到目前为止,在谷歌搜索了一整天后,我无法想出一个解决方案来告诉我在 TS 文件中的 FormGroup 中获取复选框选中的值。我附上代码。
app.component.html
<form [formGroup]="formdata">
<label>Vehicles</label><br>
<mat-radio-group>
<mat-checkbox *ngFor="let v of Vehicles" formControlName="vehicles" [value]="v.value">{{ v.option }}</mat-checkbox>
</mat-radio-group>
</form>
{{ formdata.value | json }}
app.component.ts
import { FormBuilder } from '@angular/forms';
export interface model
{
value: string; //Store value for the option
option: string; //Stores option to be displayed
}
export class FormComponent implements OnInit{
Vehicles: model[] = [{value: '2 wheelers', option: '2 wheelers'}, {value: '4 wheelers', option: '4 wheelers'}];
constructor(private fb: FormBuilder) {}
formdata = this.fb.group({
vehicles: []
});
}
我得到的输出为 true or false`` but I want the output as2 或 4 或 2,4```。
请帮帮我。
【问题讨论】:
-
你问的是 mat-radio-button 吗? material.angular.io/components/radio/overview
-
我知道你想要复选框 - 这个演示正是你想要的:stackblitz.com/edit/angular-stszta
-
@Eliseo 我正在实现 mat-checkbox 编写 mat-radio-group 的唯一原因只是将它们分组
-
@AvishekDattaRay,对我来说这不是很自然,但是您可以使用 [checked] 属性和 (change) 事件来更改表单的值,请参阅我的答案
标签: angular typescript angular-reactive-forms angular9