【问题标题】:Set other value other than default value in angular 7 dropdown在 Angular 7 下拉菜单中设置默认值以外的其他值
【发布时间】:2020-03-28 02:56:47
【问题描述】:

我有一个下拉列表,其中显示“US”作为默认值 是对的,但假设用户 来自印度,所以我希望在下拉列表中显示“印度”。如果用户来自“美国”或任何 其他国家然后它在下拉列表中显示“美国”。 所以我想将用户的当前位置存储在下拉列表中。但是 默认情况下,它应该在下拉菜单中显示“US”。如果用户来自 India 然后在下拉菜单中设置“印度”。

如果用户来自“美国”或任何其他国家/地区,则默认情况下会显示 下拉菜单中的“美国”,但如果用户来自“印度”,那么它会显示印度 下拉菜单。

app.component.ts -

   countries = [
    { name: 'USA', id: '0' },
    { name: 'India', id: '1' }
];

 public onChange() {
    const userCountry = sessionStorage.getItem(this.appConstants.StorageKeys.UserCountry);
    if (userCountry !== null || userCountry !== '') {
        return userCountry;
        console.log(userCountry);
    } else {
        return this.countries;
    }
}

Here userCountry gives the current location of user i.e; India , Us, OR Any 
other country that we fetch from the api .

app.component.html

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

当用户的当前位置为 印度或任何其他国家。 我也不想使用 ngModel 进行绑定。 请帮忙!

【问题讨论】:

    标签: angular7 dropdown


    【解决方案1】:
       countries = [
               { name: 'USA' },
               { name: 'India'}
            ];
    
       public selectedCountry: string = 'India';      
    
       <select>
       <option  *ngFor="let country of countries" [value]="country" 
       [selected]="country === selectedCountry">
       {{ country }}
       </option>
       </select>
    
       For reactive form use syntax for drodown -
    
      <select>
      <option *ngFor="let country of countries" value="{{country }}" 
      selected="country === {{selectedCountry}}">{{ country }}
      </option>
      </select>
    

    For Another way of dropdown binding reactive form you can also visit- 以反应形式使用选择控件 以下示例展示了如何以反应形式使用选择控件。

      import {Component} from '@angular/core';
      import {FormControl, FormGroup} from '@angular/forms';
    
      @Component({
      selector: 'example-app',
      template: `
      <form [formGroup]="form">
       <select formControlName="state">
        <option *ngFor="let state of states" [ngValue]="state">
          {{ state.abbrev }}
        </option>
       </select>
      </form>
    
     <p>Form value: {{ form.value | json }}</p> 
     <!-- {state: {name: 'New York', abbrev: 'NY'} } -->
      `,
     })
    export class ReactiveSelectComp {
    states = [
    {name: 'Arizona', abbrev: 'AZ'},
    {name: 'California', abbrev: 'CA'},
    {name: 'Colorado', abbrev: 'CO'},
    {name: 'New York', abbrev: 'NY'},
    {name: 'Pennsylvania', abbrev: 'PA'},
    ];
    
    form = new FormGroup({
     state: new FormControl(this.states[3]),
     });
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 2019-12-28
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-08-15
      • 2021-11-24
      相关资源
      最近更新 更多