首页 > 解决方案 > 如何将选定的下拉值传递给组件

问题描述

我是 Angular 的新手。

我正在关注这个公认的答案。 使用Angular 4根据第一个下拉列表选择第二个下拉列表

根据下拉菜单创建了下拉菜单,如下所示 -

    <select [(ngModel)]="country">
      <option *ngFor="let country of countries" [value]="country"> {{ country }} </option>
    </select>

    <select *ngIf="country" [(ngModel)]="city" [value]="city">
      <option *ngFor="let city of cities" [value]="city"> {{ city }} </option>
    </select>
    export class AppComponent {
      private map = new Map<string, string[]>([
        ['Poland', ['Warszawa', 'Krakow']],
        ['USA', ['New York', 'Austin']],
      ])

      country: string;
      city: string;

      get countries(): string[] {
        return Array.from(this.map.keys());
      }

      get cities(): string[] | undefined {
        return this.map.get(this.country);
      }

    }

现在我想——

选定值传递给组件。

我尝试像这样传递静态值 -

    <app-render country="USA" city="Austin"></app-render>

这很好用

所以,为了传递选定的值,我尝试这样 -

    <app-render [country]="country" [city]="city"></app-render>

请帮助/指导。

标签: angular

解决方案


<select [(ngModel)]="input-country">
  <option *ngFor="let country of countries" [value]="country"> {{ country }}</option>
</select>

<select *ngIf="country" [(ngModel)]="input-city" >
  <option *ngFor="let city of cities" [value]="city"> {{ city }} </option>
</select>

接着

<app-render [country]="input-country" [city]="input-city"></app-render>

推荐阅读