Formgroup Required conditioning

Asked

Viewed 262 times

0

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

I start formGroup on onInit so:

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

These 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?

  • 1

    I removed the tag angularjs, since this tag represents the angular version 1 and the doubt is in relation to the latest version.

1 answer

1


The Input is built through a Property Binding:

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

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

@Input required = true;

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

To add the 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]
     })
     //...
 }
  • I’ll try here

  • I’m getting an error, inline template:6:94 caused by: v is not a function , I think that and in building the formGroup, I did like you, you have any idea what it is?

  • I think the problem and in the way that validators and declared, I will do some checks.

  • It had a small change to work but the idea and this

  • 1

    @Williamcézar and what was this change? So I can complete the answer and help others with the same question.

  • Okay, soon put here, thank you so much for helping Felipe

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.