Home > Software engineering >  The selected value of the select attribute is not displayed. TypeScript/Angular
The selected value of the select attribute is not displayed. TypeScript/Angular

Time:02-10

I don't see anything in the item selection window. The elements are loaded from the Web APi server. Here is the photo of problem.

Component class

carsDynamic!: Array<Car>

private loadDynamicData(){
  this.dynamic.getDynamicCars().subscribe((data: Car[]) => {
  this.carsDynamic = data
})

HTML page

<select   [(ngModel)]="editedSale.carId">
  <option disabled selected>--Select--</option>  
  <option *ngFor="let car of carsDynamic"  
          value={{car.id}}>  
          {{car.brandName}}  
  </option>  
</select>

How to fix this problem ?

CodePudding user response:

Problem originates from [(ngModel)]="editedSale.carId". You have to choose, either template driven from or reactive form.

@Component({
  selector: 'select-reset-example',
  templateUrl: 'select-reset-example.html',
  styleUrls: ['select-reset-example.css'],
})
export class SelectResetExample {
  dynamic = new ReplaySubject<any>(1);
  carsDynamic: any[];
  data = [
    { id: 1, brandName: 'Audi' },
    { id: 2, brandName: 'BMW' },
  ];

  constructor() {
    this.loadDynamicData();
    this.dynamic.next(this.data);
  }

  private loadDynamicData() {
    this.dynamic.subscribe((data: Car[]) => {
      this.carsDynamic = data;
    });
  }

  onSelect(event: any) {
    console.log(event.target.value);
  }
}

export interface Car {
  id: number;
  brandName: string;
}

<select  (change)="onSelect($event)">
  <option disabled selected>--Select--</option>
  <ng-container *ngFor="let car of carsDynamic">
    <option value="{{car | json}}">{{car.brandName}}</option>
  </ng-container>
</select>

<select  (change)="onSelect($event)">
  <option disabled selected>--Select--</option>
  <ng-container *ngFor="let car of carsDynamic">
    <option value="{{car.id}}">{{car.brandName}}</option>
  </ng-container>
</select>

Look into console log. Working example: https://stackblitz.com/edit/angular-material-matselect-ybbg2t?file=app/select-reset-example.ts

  •  Tags:  
  • Related