2
votes

Angular 7 - Valide le champ de saisie uniquement si la case est cochée

J'utilise angular 7 et j'ai un formulaire avec deux champs de saisie, alors que le premier est toujours requis, le second ne devrait être requis que si une case est cochée.

J'essaie d'utiliser un FormGroup avec un validateur personnalisé:

exampleForm: FormGroup;
checked: boolean;

ngOnInit() {
  this.exampleForm = new FormGroup({
    'second': new FormControl('', [this.validateIfChecked()]),
    'first': new FormControl('example', [Validators.required])
  });
}


validateIfChecked(): ValidatorFn {
  return (control: AbstractControl): {
    [key: string]: any
  } | null => {
    if (this.checked) {
      return control.value ? null : {
        'err': true
      };
    }
    return null;
  }
}

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox [(ngModel)]=" checked" [ngModelOptions]="{standalone:true}">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>

Le problème est que la validation est effectuée uniquement lorsque le texte des deux champs de saisie est mis à jour, alors que si je coche / décoche la case à cocher l'état ne change pas et pour forcer la validation je dois changer le texte dans la deuxième zone de texte.

Ici , vous pouvez voir un exemple sur stackblitz: si vous cochez la case, le statut ne change pas.

Comment puis-je forcer la validation lorsque le statut de la case à cocher change?


1 commentaires

qu'en est-il désactivé l'entrée? REMARQUE: vous devez désactiver et activer le contrôle à l'aide de exampleForm.controls.second.disable () et exampleForm.controls.second.enable (). stackblitz.com/edit/angular-d7hj6a?file= src / app /…


3 Réponses :


1
votes

Vous pouvez ajouter dynamiquement la validation requise au contrôle de formulaire en fonction de la case à cocher cochée.

Modèle:

checkstate(){
  this.checked = !this.checked;
  if(this.checked){
     this.exampleForm.get('second').setValidators(Validators.required);
  }else{
     this.exampleForm.get('second').clearValidators();
  }
  this.exampleForm.get('second').updateValueAndValidity();
}

Composant:

<form [formGroup]="exampleForm">
  <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
  </mat-form-field>
  <mat-checkbox [(ngModel)]="checked" [ngModelOptions]="{standalone:true}" (click)="checkstate()">Make second input field required</mat-checkbox>
  <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
  </mat-form-field>
</form>


0 commentaires

2
votes

Vous devez utiliser la validation crossfield. Incluez la case à cocher dans votre groupe de formulaire

ngOnInit() {
    this.exampleForm = new FormGroup({
    'second': new FormControl(''),
    'checked': new FormControl(false),
    'first': new FormControl('example')
    }, [this.validateIfChecked()]);
}


validateIfChecked(): ValidatorFn {
    return (form: FormGroup): ValidationErrors | null => {
    const checked = form.get('checked');
    const second= form.get('second');
    if (checked && !second) {
        return {
        'err': true
        };
    }
    return null;
    }
}
<form [formGroup]="exampleForm">
    <mat-form-field>
    <input matInput placeholder="first" formControlName="first">
    </mat-form-field>
    <mat-checkbox formControlName="checked">Make second input field required</mat-checkbox>
    <mat-form-field>
    <input matInput placeholder="second" formControlName="second">
    </mat-form-field>
</form>

Dans ce cas, si «coché» est vrai, alors «deuxième» est requis

si dans doute https://angular.io/guide/form-validation#cross-field -validation


0 commentaires

2
votes

Si vous ne souhaitez pas inclure la valeur de la case à cocher dans votre formulaire, vous pouvez créer un contrôle de formulaire distinct, qui n'est pas inclus dans votre formulaire. En fonction de la valeur de la case à cocher, vous pouvez effacer les validateurs ou ajouter le validateur requis:

<mat-checkbox [formControl]="checked">Make second input field required</mat-checkbox>

Et le modèle approprié:

checked = new FormControl(false);

// ...

this.checked.valueChanges.subscribe((bool: boolean) => {
  bool ? this.exampleForm.get('second').setValidators(Validators.required) : 
         this.exampleForm.get('second').clearValidators();
  this.exampleForm.get('second').updateValueAndValidity();
});

Votre fourchue StackBlitz p >


0 commentaires