我请求您合作,指示我如何验证取决于单选按钮上所选值的文本字段;实际上我需要的是仅在选择选项 4 时激活观察字段,但表单将其显示为无效。
当我选择选项四时,它告诉我它是字段 observacionA 所必需的,但是当我填写它时,表单无效
类
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}}
最佳答案
当验证器有效时,您应该返回 null
而不是像这样的对象:
{
return: null
}
应该是:
if(observacionA){
return null;
还有一点:
<button [disabled]="valido()"
^^^
add this because it's method
关于javascript - 根据另一个 Angular 的值验证字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46519309/