【发布时间】:2017-10-02 03:58:49
【问题描述】:
请求您合作,说明我如何验证取决于单选按钮上选择的值的文本字段;实际上,我需要的是仅在选择选项 4 时才激活观察字段,但表单将其显示为无效。
当我选择选项四时,它告诉我字段 observacionA 是必需的,但是当我填写它时,表格如下无效
Class
export class AppComponent {
testForm: FormGroup;
msgError: string = 'Este Campo es obligatorio';
opciones = [
{ nombre: 'N1', valor: 1 },
{ nombre: 'N2', valor: 2 },
{ nombre: 'N3', valor: 3 },
{ nombre: 'Otra Respuesta', valor: 4 },
];
constructor(public fb: FormBuilder) {
this.testForm = this.fb.group({
'opcionA': ['', [Validators.required]],
'observacionA': new FormControl(null)
}, {
validator: this.specificValue
});
}
valido(): boolean {
return !this.testForm.valid;
}
specificValue(group: any) {
if (!group.controls.opcionA || !group.controls.opcionA.value) return;
const opcionA = group.controls.opcionA.value;
let observacionA = group.controls.observacionA.value;
if (opcionA == '4') {
if (observacionA) {
return {
return: null
};
} else {
return {
isRequired: true
};
}
}
}
guardar() {
console.log(this.testForm.value);
}
}
Html
<h1>Form</h1>
<form [formGroup]="testForm" (ngSubmit)="guardar()" novalidate>
<label *ngFor="let opcion of opciones">
<input type="radio"
formControlName="opcionA"
required
[value]="opcion.valor">{{opcion.nombre}}
</label>
<div *ngIf="testForm.get('opcionA').invalid">
{{ msgError }}
</div>
<div *ngIf="testForm.value.opcionA === 4">
<textarea formControlName="observacionA"></textarea>
<div *ngIf="testForm.get('observacionA').invalid">
{{ msgError }}
</div>
</div>
<br>
<hr>
<button [disabled]="valido"
type="submit">
Save
</button>
</form>
{{testForm.valid}}
【问题讨论】:
-
你能把它放在 plnkr 或 stackblitz 中吗?
-
好的,你已经可以看到我的应用程序的演示了@brijmcq
标签: javascript forms angular