我有一个简单的自定义单选按钮控件。HTML:
<label class="radiobutton-container" >
<ng-content></ng-content>
<input type="radio" [value]="value" [name]="name" [disabled]="disabled" (change)="handleChange($event)" [checked]="checked"/>
<span [ngClass]="{'checkbase': true,
'checkmark' : checked
}"></span>
</label>
一般来说,它工作得很好,我可以判断它是否被检查并放入组中,等等。但是,当我在表单中使用它时,我只将组的值设置为"true",而不是组件的值:
<form #form="ngForm" >
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value1'" >Value 1</my-radiobutton>
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value2'" >Value 2</my-radiobutton>
<my-radiobutton [ngModel]="mymodel" [name]="'options'" [value]="'value3'" >Value 3</my-radiobutton>
</form>
<p>form value:</p>
<pre>{{ form.value | json }}</pre>
当我打印表单的值时,它只是"选项:true",而不是"value1"、"value2"等。
不确定我做错了什么。感谢您的帮助!
使用数组而不是一次又一次地调用组件,请参考以下代码App.component.html
`<form>
<app-my-radiobutton [inputList]="radioList"
(changedInput)="onValueChange($event)"></app-my-radiobutton>
</form>
<pre *ngIf="title">
{{title.form.value | json}}
</pre>`
应用程序组件.ts
title: NgForm;
radioList = ['Male', 'Female'];
onValueChange(event) {
this.title = event
}
Myradiobutton.组件
@Input() inputList = [];
@Output() changedInput = new EventEmitter<any>();
inputData: string;
constructor() { }
ngOnInit() {}
onChange(event, form) {
this.changedInput.emit(form)
}
Myradiobutton.HTML
`<div class="container">
<form #form="ngForm">
<div *ngFor="let item of inputList; let i = index">
<input type="radio" id="{{item+i}}" name="gender" value="{{item}}"
[(ngModel)]="item" (change)="onChange($event, form)">
<label for="male">{{item}}</label><br>
</div>
</form>
</div>`
输出
{"性别":"男性"}或{"性别":"女性男性"}