How to unlock the fields according to what the user types?

Asked

Viewed 35 times

0

I’m making a form with 3 fields, where the first fields is unlocked and the others blocked. They unlock according to the first field, for example:

User typed in the first field -> unlocks the second -> typed in the second field -> unlocks the third

I implemented it that way, but it didn’t work. What I’m doing wrong?

<div class="ui-g-12 ui-md-3">
    <input id="dia" label="dia" minLenght="2" maxlength="2" (keyup)="showSearch($event)"></input>
  </div>
<div class="ui-g-12 ui-md-3">
    <input id="mes" label="Mes" (keyup)="showSearch($event)"></msp-input-text>
  </div>
  
  <div class="ui-g-12 ui-md-3">
    <autocomplete id="ano" label="ano" (keyup)="showSearch($event)">
    </autocomplete>
  </div>

showSearch(event){
   this.form.get('dia').valueChanges.subscribe(value => {
   if(value){
    this.form.get('campo2').enable
   }
  })
}

1 answer

0

Opa, enable is a enable() method to enable the field or disable() to disable

this.form.get('campo2').enable()

In addition, the form in the template must contain a [formGroup]="myFormulario" and formControlName to connect the input with a variable in the Component

template would look like this

<form [formGroup]="meuFormulario">

<input formControlName="nomeDoMeuCampoDia" id="dia" (keyup)="showSearch($event)">

<input formControlName="nomeDoMeuCampoMes" id="mes" (keyup)="showSearch($event)">

<input formControlName="nomeDoMeuCampoAno" id="ano" (keyup)="showSearch($event)">

</form>

Component would look like this

constructor(private form: FormBuilder){
  this.meuFormulario = this.form.group({
  'nomeDoMeuCampoDia': ''
  'nomeDoMeuCampoMes': [{value: '', disabled: true}],
  'nomeDoMeuCampoAno': [{value: '', disabled: true}],
  })
}

showSearch(event){
    const id = event.target.id;

    switch (id) {
      case 'dia':
        this.meuFormulario.get('nomeDoMeuCampoMes').enable();
        break;
      case 'mes':
        this.meuFormulario.get('nomeDoMeuCampoAno').enable();
        break;
    }
})
  • then the method is right, would only be added the method? I was in doubt for the third field

  • the method enables or disables the fields... The logic for your problem would be more or less what I sent above. I removed the valueChanges pq it detects changes in the form/input you don’t need it, because you already took an event that identifies these changes in the input that is the (keyup)

Browser other questions tagged

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