我正在开发Angular 2应用程序,在表单中我输入了类型复选框,它可能有多个值。我想在每次更改事件时都读取所有选中的值,但不确定如何操作。目前我只能读一个值。
<div *ngSwitchCase="'checkbox'"> <small>checkbox</small>
<div *ngFor="let opt of question.options" >
<label class="container-vertical"> {{opt.value}}
<input type="checkbox"
[formControlName]="question.key"
[name]="opt.name"
[value]="opt.key"
[checked]="opt.selectedOption"
(change)="onChangeValue($event)"
(blur)="onChangeValue($event)"
>
<span class="checkmark2"></span>
</label>
</div>
</div>
handleCheckBoxChange (event: any) {
console.log(".............. ",event);
console.log("selected Value ", event.target.value);
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
console.log("question id", idAttr);
}
答案 0 :(得分:0)
您的HTML应该使用ngModel进行双向数据绑定。
<div *ngSwitchCase="'checkbox'"> <small>checkbox</small>
<div *ngFor="let opt of question.options" >
<label class="container-vertical"> {{opt.value}}
<input type="checkbox"
[formControlName]="question.key"
[name]="opt.name"
[value]="opt.key"
[(ngModel)]="opt.selectedOption"
(change)="onChangeValue()"
(blur)="onChangeValue()"
>
<span class="checkmark2"></span>
</label>
</div>
</div>
在您的TS文件中,您可以检查question
对象的options
属性值,该属性值将是具有属性的对象数组( name,key,selectedOption )
TS文件
onChangeValue() {
console.log(this.question);
}