验证字段取决于另一个Angular的值

时间:2017-10-02 03:58:50

标签: javascript forms angular

我请求您的合作,以指明我如何验证取决于单选按钮上所选值的文本字段;实际上我需要的是仅在选择选项4时激活观察字段,但表单将其显示为无效。

当我选择选项4时,它告诉我字段observacionA是必需的,但是当我填写它时表单跟随无效

following-sibling::

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

Demo in stackblitz

2 个答案:

答案 0 :(得分:0)

当验证器有效时,您应该返回null而不是像

这样的对象
{
  return: null
}

应该是:

if(observacionA){
  return null;

还有一点需要注意:

<button [disabled]="valido()"
                          ^^^
                     add this because it's method

<强> Stackblitz example

答案 1 :(得分:0)

可能还有很多其他解决方案,但我认为这是最简单的解决方案。

HTML:

<md-radio-group formControlName="opcionA" required >
   <md-radio-button *ngFor="let opcion of opciones" (change)="validField=opcion.valor" [value]="opcion.valor" >
                    {{opcion.nombre}}
   </md-radio-button>
</md-radio-group>
<md-form-field *ngIf="(validField==4) ? true : false">
    <textarea mdInput
          formControlName="observacionA"
          [errorStateMatcher]="myErrorStateMatcher"
          >
    </textarea>
<md-error>{{ msgError }}</md-error>

打字稿:

 testForm: FormGroup;
 opciones = [
  { nombre: 'A', valor: 1 },
  { nombre: 'B', valor: 2 },
  { nombre: 'C', valor: 3 },
  { nombre: 'Otra Respuesta', valor: 4 },
 ];

validField:number; //declared variable for html
constructor (public fb: FormBuilder) { }
...

希望这会对你有所帮助。

相关问题