【问题标题】:How to pass selected dropdown value to a component如何将选定的下拉值传递给组件
【发布时间】:2020-02-11 01:12:59
【问题描述】:

我是 Angular 的新手。

我正在关注这个公认的答案。 Select second dropdown based on first dropdown using Angular 4

我创建了dropdown based on dropdown如下 -

    <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>

请帮助/指导。

【问题讨论】:

  • 这不是你使用选择标签的方式:&lt;select *ngIf="country" [(ngModel)]="city" [value]="city"&gt; &lt;option *ngFor="let city of cities"&gt; {{ city }} &lt;/option&gt; &lt;/select&gt;
  • [value]="city" 应该在选项中
  • ``` ```试过这个。
  • 你的意思是设置默认值还是预加载选择值?
  • 所选值将在变量city 处更新,因为您使用了[(ngModel)]="city"

标签: angular


【解决方案1】:

试试这个

<option *ngFor="let city of cities" [ngValue]="city"> {{ city }} </option>

【讨论】:

  • [value]="city"
  • 请让我试试。
【解决方案2】:
<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>

【讨论】:

  • &lt;app-render [country]="input-country" [city]="input-city"&gt;&lt;/app-render&gt; 没用。但是&lt;p&gt;Selected city: {{city}}&lt;/p&gt; 工作
  • 我在 .ts ``` @Input() public country: string; @Input() 公共城市:字符串; ngOnInit() { console.log('Country', this.country); console.log('City', this.city); }```
  • 组件似乎已经加载,选择值后未加载。所以在 my.component.ts 文件中,这些值是 NaN.
【解决方案3】:

感谢大家的帮助/意见。下面的代码有效 -

<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>

然后

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-20
    相关资源
    最近更新 更多