Marcelo Bicalho
Marcelo Bicalho

Reputation: 11

How to update value MatSelect in Angular 5

Staff all right?

I'm in need of a help is the following how do I set a value when loading the form in the MatSlected component of the Angular Material using reactive forms, when a value comes from a service. I've tried several ways but never update the value on my screen. Can someone help me?

Hugs

FuncionarioController

export class FuncionarioPopupComponent implements OnInit, OnDestroy {





public funcionarioForm: FormGroup;

editMode:boolean = false;

perfisSubscription : Subscription;

funcionarioSubscription: Subscription;

perfis: Perfil[] = [];

funcionarios: Funcionario[] =[];

funcionarioSelected: any;




  constructor(private perfilService: PerfilService, private funcionarioService:
    FuncionarioService, @Inject(MAT_DIALOG_DATA) public data:
    any, public dialogRef: MatDialogRef<FuncionarioPopupComponent>,
    private fb: FormBuilder) {


    }

  ngOnInit() {
    this.funcionarioSelected = this.data.payload
    this.buildItemForm(this.funcionarioSelected)
    this.loadFuncionariosPage();
    this.initPerfis();


  }

  initCombosValues(){
    if(this.editMode){
      this.funcionarioForm.controls['isam'].setValue(this.funcionarioSelected.isam);
      this.funcionarioForm.controls['gerente'].setValue(this.funcionarioSelected.gerente);

    }

  }



  loadFuncionariosPage() {
    this.funcionarioSubscription = this.funcionarioService.getAllFuncionarios('').subscribe(
      (funcionarios) => {
        this.funcionarios = funcionarios;
        this.initCombosValues();
      });
  }

  initPerfis(): any {
    this.perfisSubscription = this.perfilService.getAllPerfis().subscribe((resp: Response) =>{
      if(resp.data){
        this.perfis = <Perfil[]>resp.data;
      }
    })
  }

  buildItemForm(func: any): any {
    this.editMode = func.id != null || func.id != '' ? true : false;
    this.funcionarioForm = this.fb.group({
      id: [func.id || ''],
      nome: [func.nome || '', [Validators.required]],
      email: [ func.email || '', this.editMode ? [] : [Validators.required, Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]],
      cpf: [func.cpf || '', [Validators.required]],
      matricula:[func.matricula || ''],
      isam: [func.isam || ''],
      gerente: [func.gerente || ''],
      password: [func.password || '', this.editMode ? null : [Validators.required]],
      confirmPassword: [func.confirmPassword || '', this.editMode ? null :[Validators.required]],
      perfis: [this.perfis|| []]
    });
    if(this.editMode){
      this.funcionarioForm.controls['isam'].valueChanges.subscribe(func =>
        this.funcionarioSelected.isam = func);
      this.funcionarioForm.controls['gerente'].valueChanges.subscribe(func =>
        this.funcionarioSelected.gerente = func);
    }

  }
  onChangePerfil(event, perfil: Perfil) {
    perfil.checked = !perfil.checked;
  }


  comparePerfis(prf1: Perfil, prf2: Perfil): boolean{
      return prf1 && prf2 && prf1.id === prf2.id;
  }

  submit() {
    this.dialogRef.close(this.funcionarioForm.value)
  }

  ngOnDestroy(): void {
    if(this.perfisSubscription){
      this.perfisSubscription.unsubscribe();
    }
    if(this.funcionarioSubscription){
      this.funcionarioSubscription.unsubscribe
    }
  }
<div fxFlex="50" class="pr-1">
          <mat-form-field class="full-width">
            <mat-select placeholder="ISAM" formControlName="isam">
              <mat-option>--</mat-option>
              <mat-option *ngFor="let func of funcionarios" [value]="func">
                {{func.nome}}
              </mat-option>
            </mat-select>
          </mat-form-field>
        </div>

      <div fxFlex="50" class="pr-1">
        <mat-form-field class="full-width">
          <mat-select placeholder="Gerente de Conta" formControlName="gerente">
            <mat-option>--</mat-option>
            <mat-option *ngFor="let func of funcionarios" [value]="func">
              {{func.nome}}
            </mat-option>
          </mat-select>
        </mat-form-field>
      </div>

Upvotes: 0

Views: 1024

Answers (1)

Marcelo Bicalho
Marcelo Bicalho

Reputation: 11

I solved it this way:

buildItemForm(func: any): any {
    this.editMode = func.id != null || func.id != '' ? true : false;
    this.funcionarioForm = this.fb.group({
      id: [func.id || ''],
      nome: [func.nome || '', [Validators.required]],
      email: [ func.email || '', this.editMode ? [] : [Validators.required, Validators.pattern("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")]],
      cpf: [func.cpf || '', [Validators.required]],
      matricula:[func.matricula || ''],
      isam: [func.isam || ''],
      gerente: [func.gerente || ''],
      password: [func.password || '', this.editMode ? null : [Validators.required]],
      confirmPassword: [func.confirmPassword || '', this.editMode ? null :[Validators.required]],
      perfis: [this.perfis|| []]
    });
    if(this.editMode){
      this.funcionarioForm.controls['isam'].setValue(this.funcionarioSelected.isam, { onlySelf: true });
      this.funcionarioForm.controls['gerente'].setValue(this.funcionarioSelected.gerente, { onlySelf: true });
      this.funcionarioForm.controls['perfis'].setValue(this.funcionarioSelected.perfis, { onlySelf: true })
    }

  }
  
  
  compareById(obj1, obj2) {
    return obj1.id === obj2.id;
  }
<mat-form-field class="full-width">
            <mat-select placeholder="ISAM" formControlName="isam" [compareWith]="compareById">
              <mat-option>--</mat-option>
              <mat-option *ngFor="let func of funcionarios" [value]="func">
                {{func.nome}}
              </mat-option>
            </mat-select>
          </mat-form-field>

Upvotes: 1

Related Questions