Change formBuilder array value

Asked

Viewed 520 times

0

I’m looking for a solution to be able to change the value of the array in formbuilder.

My code is only changing the "visual" and not what should actually be changed. follows codes.

Online: stackblitz

<div *ngFor="let endereco of form.get('enderecos').controls; let i = index;" formArrayName="enderecos">
        <div [formGroupName]="i">

      <label class="">CEP</label>
      <input class='' formControlName="nu_cep" (keyup)="alterarEndereco(i,endereco)">

      <br /><br />

      <label class="">Estado</label>
      <select class='' formControlName='estado'>
        <option *ngFor='let estado of estados' [value]='estado.uf'>{{estado?.nome}}</option>
      </select>

    </div>
  </div>

estados: any[]=[{uf:'GO',nome:"GOIAS"},{uf:'RR',nome:"RORAIMA"}];    
  form: FormGroup;
  constructor(private formBuilder: FormBuilder) { }

  alterarEndereco(i,endereco) {
    // (<FormControl>this.form.controls['enderecos'][i].controls.estado).setValue('RR');
    endereco.value.estado = 'GO'
  }

  initializeFormEmpty() {
    this.form = this.formBuilder.group({
      enderecos: this.formBuilder.array([this.enderecoItem()])
    })
  }
  enderecoItem(): FormGroup {
    return this.formBuilder.group({
      nu_cep: this.formBuilder.control('', [Validators.required]),
      estado: this.formBuilder.control('RR', [Validators.required]),
    })
  }

Online: stackblitz

1 answer

0

To change the formsReactive value use the setValue method()

 alterarEndereco(i:number,endereco:FormGroup) {
    // (<FormControl>this.form.controls['enderecos'][i].controls.estado).setValue('RR');
    endereco.get('estado').setValue('GO') //= 'GO'
  }

Browser other questions tagged

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