2

I need simple code help. If I choose any particular letter then corresponding countries should be displayed, in my current position I am not able to do it dynamically. For example if i choose letter A then countries pertaining to those should be displayed outside the select.

<select [(ngModel)]="selectedOption">
        <option *ngFor="let o of options">
          {{o.letter}}
        </option>
      </select>

<p *ngFor="let o of options">Countries are: {{ o.countries }}</p>

export class AppComponent {
  selectedOption: string;

  options = [
    { letter: "A", countries: ["Afghanistan", "Albania", "Argentina"] },
    { letter: "B", countries: ["Bangladesh", "Bahamas", "Bahrain"] }
  ]

}

If A chosen then Afghanistan Albania .... If B chosen then .... If C chosen then .... I should be able to expand array in future.

R.H
  • 318
  • 2
  • 12

2 Answers2

2

You can use ngValue instead of using ngFor. You can refer this answer. Here is the working example.

Your code becomes

<select [(ngModel)]="selectedOption">
  <option *ngFor="let o of options" [ngValue]="o">
    {{o.letter}}
  </option>
</select>

<!-- Just to debug and display selected object -->
{{selectedOption | json}} 

<p>{{selectedOption.countries}}</p>
Laxmikant Dange
  • 7,606
  • 6
  • 40
  • 65
0

You can try this

<p *ngFor="let o of options">
 <label *ngIf="o.letter === selectedOption">Countries are: {{ o.countries }}<label>
</p>
Bhagwat Tupe
  • 1,905
  • 1
  • 13
  • 28
Seba Cherian
  • 1,755
  • 6
  • 18