我是使用角度动态表单的新工作,我遇到了单选按钮的问题,当我选择单选按钮选项时,所选单选按钮的值不会反映在FormGroup的实例中。为了说明这种情况,我将向您展示相关代码:
我有两个组成部分:
动态表单通过toFormGroup(answers):FormGroup
方法接收答案列表,答案列表在动态表单问题中呈现为电台广告组件,动态表单构建一个表单,该表单将传输到动态表单问题组件。
在每个组件的代码下面:
动态form.html
<form (ngSubmit)="onSubmit()" [formGroup]="form">
<div *ngFor="let answer of answers$ | async">
<app-question [answer]="answer" [form]="form"></app-question>
</div>
</form>
动态form.ts
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.css'],
providers: [ AnswerControlService ]
})
export class DynamicFormComponent implements OnInit {
@Input() answers$: Observable<AnswerBase<any>[]>;
form: FormGroup;
payLoad = '';
constructor(private qcs: AnswerControlService, private service: DynamicFormService) { }
ngOnInit() {
this.form= new FormGroup({});
this.answers$.subscribe(a=>this.form = this.qcs.toFormGroup(a));
}
onSubmit() {
this.payLoad=JSON.stringify(this.form.value);
}
动态外形question.html
<div [formGroup]="form">
<label [attr.for]="answer.id">{{answer.label}}</label>
<div [ngSwitch]="answer.controlType">
<input *ngSwitchCase="'radio'" [formControlName]="answer.controlName"
[id]="answer.id" [type]="answer.type" [value]="answer.label">
</div>
<div class="errorMessage" *ngIf="!isValid">{{answer.label}} is required</div>
动态外形question.ts
@Component({
selector: 'app-question',
templateUrl: './dynamic-form-question.component.html',
styleUrls: ['./dynamic-form-question.component.css']
})
export class DynamicFormQuestionComponent {
@Input() answer: AnswerBase<any>;
@Input() form: FormGroup;
@Input() currentQuestion:Question;
get isValid() {
return this.form.controls[this.answer.controlName].valid;
}
}
当我选择单选按钮选项时,会出现两个问题:
答案 0 :(得分:0)
question-radio.ts
import { QuestionBase } from './question-base';
export class RadioQuestion extends QuestionBase<string> {
controlType = 'radio';
options: {key: string, value: string}[] = [];
constructor(options: {} = {}) {
super(options);
this.options = options['options'] || [];
}
}
question.service.ts
new RadioQuestion({
key: 'sex',
label: 'Sex',
type: 'radio',
options: [
{key: 'Male', value: 'm'},
{key: 'Female', value: 'f'}
],
required: true,
order: 4
})
dynamic-form-question.html
<div *ngSwitchCase="'radio'">
<label *ngFor="let opt of question.options">
{{opt.key}}
<input
type="radio"
[name]="question.key"
[formControlName]="question.key"
[value]="opt.value">
</label>
</div>