Search code examples
angulartypescriptformbuilder

Mat-select default value didn't work with multipule ways


I'm using mat-select and I need to set a default value for it when the user tries to update info. I'm using patchValue to update form values and set default values and it works on my other inputs except for the mat-select.

Here is my template:

<form [formGroup]="profileForm" class="event-form w-100-p" fxLayout="column" fxFlex>
 ...

    <mat-form-field appearance="outline" fxFlex="100" required>
        <mat-label>Departement*</mat-label>
        <mat-select formControlName="Département">
             <mat-option *ngFor="let dept of departements" [value]="dept.id">
                {{dept.name}}
             </mat-option>
        </mat-select>
        <mat-icon matSuffix class="secondary-text">outlined_flag</mat-icon>
        <mat-error>Selecter le departement</mat-error>
    </mat-form-field>

And here is my component.ts:

profileForm = this.fb.group({
    Nom_de_famille: ['' ,Validators.required],
    Prénom: ['' ,Validators.required],
    email: ['', [Validators.email, Validators.required]],
    Code_personnel: [Validators.compose([Validators.min(1000), Validators.max(9999)])], 
   //Validators.required
    N_tel: [''],
    birthday: [''],
    adresse: [''],
    lieu:[''],
    CIN:['',Validators.compose([Validators.min(10000000), Validators.max(99999999)])],
    Genre:[''],
    N_permis:[''],
    Département: ['',Validators.required]
  });

 ngOnInit() {
    this.ListDepartmentEntity.forEach(e=>{
      x++;
      this.departements.push({id:x, name:e.Name}); // to fill departement options
   });
   this.setdefaultformvalues(this.indata.SendData);
}

setdefaultformvalues(row) {
    let pos = 0, posDep = 0;
    this.departements.forEach(e => {
          pos++
          if(row.DepartmentId==e.id){
            posDep = pos; // to get current deparetement position
          }
    });
    if(row.CIN==''){
      row.CIN = null;
    }
   console.log(row.DepartmentString);
    this.profileForm.patchValue({
      Nom_de_famille: [row.FirstName],
      Prénom: [row.LastName],
      email: [row.Email],
      Code_personnel: [row.DriverCode],
      N_tel: [row.Tel],
      birthday: null,
      adresse: [row.Address],
      lieu:[row.BirthPlace],
      CIN:[row.CIN],
      Genre:[row.DriverLicenseType],
      N_permis:[row.DriverLicenseNumber],
      Département: this.departements[posDep]
    });
  }

Rq: I've tried with [(value)] and ngModel before and nothing happen.


Solution

  • Your value is id

    [value]="dept.id"

    Change to

    this.profileForm.patchValue({
      ... 
      Département: this.departements[posDep].id
    });