Home > Enterprise >  Angular: Show value in a select
Angular: Show value in a select

Time:07-07

I have two select and I show value if they exist:

page.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  customer: any = {
    city: '',
    state: '',
  };

  ngOnInit() {
    // I recover this info from BE
    this.customer.state = 'England';
    this.customer.city = 'London';
  }
}

page.html

  <div >
  <label >State *</label>
  <div
    
    [ngClass]="
      customer.state ? 'input-group input error' : 'input-group input-error'
    "
  >
    <select
      id="state"
      
      [(ngModel)]="customer.state"
      [ngModelOptions]="{ standalone: true }"
      (change)="onChangeProvinceForState($event.target.value)"
      appTab
      tabIndex="14"
    >
      <option disabled value="">Select State</option>
      <option
        *ngFor="let state of stateList"
        ngDefaultControl
        [value]="state.name"
      >
        {{ state.name }}
      </option>
    </select>
  </div>
</div>

<div >
  <label >City *</label>
  {{ this.customer.city }}
  <div
    
    [ngClass]="customer.city ? 'input-group' : 'input-group input-error'"
  >
    <!-- <span  *ngIf="existingCustomer">{{customer.city}}</span> -->
    <select
      id="city"
      name="city"
      
      [(ngModel)]="customer.city"
      [ngModelOptions]="{ standalone: true }"
      appTab
      tabIndex="15"
    >
      <option value="">Select City</option>
      <option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
        {{ city }}
      </option>
    </select>
  </div>
</div>

https://stackblitz.com/edit/angular-wyendp?file=src/app/app.component.html

I recover the city and state from an api call, but I don't understand how to show in the select directly

EDIT:

onChangeStateForCity(e) {
        console.log("e ", e)
        let countiesObservable = this.citiesService.getAllState();
        countiesObservable.pipe(untilDestroyed(this)).subscribe((data: any) => {
            this.citiesList = data[e];
        });
    }

CodePudding user response:

You are missing the declaration of properties stateList and citiesList. I have modified your SB, to generate some static dropdown down options. You can easily assign these variables to the response you get from your API.

Stackblitz demo

app.component.ts (defined the variables):

stateList = [
    'England',
    'France'
  ]

  citiesList = [
    'London',
    'Paris'
  ]

app.component.html (bind them in template):

<option *ngFor="let state of stateList" ngDefaultControl [value]="state">
<option *ngFor="let city of citiesList" ngDefaultControl [value]="city">
  • Related