Home > other >  Selected option Mat-select with Observable
Selected option Mat-select with Observable

Time:04-09

I want to select an option by default in my mat-select but it doesn't work. I want the select to have default option selected as the activity get on my modeleService. I don't know if the problem comes from Observable or if it comes from the referential equality.

What I've tried :

HTML :

 <form [formGroup]="modeleForm" (ngSubmit)="onSubmit()">
   <mat-form-field *ngIf="activities$ | async as activities" appearance="legacy">
     <mat-label>Activité</mat-label>
     <mat-select formControlName="activite">
       <mat-option *ngFor="let activity of activities" [value]="activity">
         {{ activity.titre }}
       </mat-option>
     </mat-select>
   </mat-form-field>
 </form>

And the TS :

  modeleForm = this.fb.group({
    titreActivite: ['', { validators :[Validators.required]}],
    sousTitreActivite: ['', { validators :[Validators.required]}],
    activite: ['', { validators :[Validators.required]}],
    active: [false, { validators :[Validators.required]}],
    raisons: ['', { validators :[Validators.required]}],
    dateModele: ''
  });

  activitySelected : any;

  activities$: Observable<Activity[]>;

  getActivities(){
    this.activities$ = this.activitesService.get()
  }

  ngOnInit(): void {
    this.getActivities()
    this.activities$.subscribe( data => {
      this.activitySelected = data[data.findIndex(lst => lst.id == 866)]
    })
    this.route.queryParams
      .subscribe(params => {
        if(params['modeleId']){
          this.modeleService.getById(params['modeleId']).subscribe(data => {
            this.modeleForm.patchValue({
              titreActivite: data.titreActivite,
              sousTitreActivite: data.sousTitreActivite,
              activite: this.activitySelected, (I also tried data.activite)
              active: data.active,
              dateModele: data.dateModele,
              raisons : data.raisons,
              questionnaire : {
              titre : "",
              questionTrees : []
            }
          })
        })
       }
      }
    );
  }

CodePudding user response:

With the attribute [(value)] as in the small sample below it should work (full example here):

<form [formGroup]="fg">
  <mat-form-field>
    <mat-select formControlName="cars" [(value)]="selectedCarName">
      <mat-option *ngFor="let car of cars" [value]="car.name">{{ car.name }}</mat-option>
    </mat-select>
  </mat-form-field>
</form>

and an excerpt from the class code:

export class AppComponent {
  cars = [
    { id: 1, name: 'Volvo' },
    { id: 2, name: 'Saab' },
    { id: 3, name: 'Opel' },
    { id: 4, name: 'Audi' },
  ];
  selectedCarName = this.cars[2].name;
  fg: FormGroup;

  ngOnInit(): void {
    this.fg = new FormGroup({
      cars: new FormControl(this.selectedCarName, { validators: [Validators.required] })
    });

    this.fg.valueChanges.subscribe(x => console.log(x));
  }
  • Related