FormGroup Required condition

1

I have a component address which has a form , it will be requirido in some places and others not so I intend to use a @input required = false; variable to do this.

I start the formGroup in onInit like this:

     buildForm(): void {
    this.formGroup = this.fb.group({
      cep: [
        '', [
          Validators.required
        ]
      ],
      uf: [
        '', [
          Validators.required
        ]
      ],
}

Here are some of the fields:

<div class="col-lg-4 col-md-4 col-sm-4">
  <div class="form-group">
    <label for="uf" class="required">UF:</label>
    <ss-dropdown formControlName="uf" (onChange)="onChangeUf($event.value)" class="component" [options]="ufs" label="label" value="value"></ss-dropdown>
    <div *ngIf="formErrors.uf" class="form-errors">
      {{ formErrors.uf }}
    </div>
  </div>
</div>
<div class="col-lg-14 col-md-14 col-sm-14">
  <div class="form-group">
    <label for="cidade" class="required">Município:</label>
    <p-autoComplete id="cidade" minLength="5" formControlName="cidade" class="component"></p-autoComplete>
    <div *ngIf="formErrors.cidade" class="form-errors" maxlength="50">
      {{ formErrors.cidade }}
    </div>
  </div>
</div>

And so I call my component:

 <ss-endereco #endereco [endereco]="cliente?.endereco"></ss-endereco>

How do I leave the required dynamic in this case?

    
asked by anonymous 08.03.2018 / 19:19

1 answer

2

Input is built through a property binding :

<ss-endereco #endereco 
             [endereco]="cliente?.endereco" 
             [required]="false">
</ss-endereco>

In the component script, you can initialize Input with a true value, for example:

@Input required = true;

Therefore, when no value is entered, true will be assumed for the variable required .

To add Validators.required dynamically, just use the variable required :

 buildForm(): void {
     let validators = [];

     if(this.required)
         validators.push(Validators.required);

     this.formGroup = this.fb.group({
         cep: ['', validators],
         uf: ['', validators]
     })
     //...
 }
    
08.03.2018 / 19:41