【问题标题】:Could not set the default value of selection at Angular 6 [duplicate]无法在 Angular 6 处设置默认选择值 [重复]
【发布时间】:2019-01-25 15:08:29
【问题描述】:

最近我开始工作 Angular 6。我在为 Select 元素设置默认值时发现问题。事实上,我正在寻找基于对象的 Select 元素。这是我的 HTML

.html 文件:

<div>
  Select The Country
  <select [(ngModel)]="SelectedCountry3">
    <option *ngFor="let country of countryList" [ngValue]="country">{{country.CountryName}}</option>
  </select>
</div>
<div>
  Selected Coutry is : <b>{{SelectedCountry3.CountryName}} -- {{SelectedCountry3.Id}} </b>
</div>

.ts 文件:

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

@Component({
  selector: 'app-angular-drop-down',
  templateUrl: './angular-drop-down.component.html',
  styleUrls: ['./angular-drop-down.component.css']
})
export class AngularDropDownComponent  {


  countryList: CountryM[];

  SelectedCountry3: CountryM;
  constructor() {

    this.countryList = [
      { Id: 1, CountryName: "Bangladesh" },
      { Id: 2, CountryName: "India" },
      { Id: 3, CountryName: "Pakistan" },
      { Id: 4, CountryName: "Srilanka" },
      { Id: 5, CountryName: "Mayenmar" },
      { Id: 6, CountryName: "Bhutan" },
      { Id: 10, CountryName: "Maldivs" }
    ];

    this.SelectedCountry3 = { Id: 2, CountryName: "India" };

  }

  trackByFn(index, item) {
    return item.Id; // or item.id
  }

  }



interface CountryM {
  Id: number;
  CountryName: string;

}

问题是当从 Select 元素中选择值时,我得到了 Country 对象,但我无法通过 Select 设置默认值 国家对象。在 AngularJS 中它可以工作。但在 Angular 中却没有。有人知道为什么吗?还是我错过了什么?

【问题讨论】:

    标签: angular angular5 angular6


    【解决方案1】:

    使用 compareWith compareWith 接受一个有两个参数的函数:option1 和 option2。如果给出了 compareWith,Angular 会根据函数的返回值选择选项。

    HTML

    <div>
      Select The Country
      <select [(ngModel)]="SelectedCountry3" [compareWith]="compareFn">
        <option *ngFor="let country of countryList" [ngValue]="country"> 
        {{country.CountryName}}</option>
      </select>
    </div>
    <div>
    
      Selected Coutry is : <b>{{SelectedCountry3.CountryName}} -- 
     {{SelectedCountry3.Id}} </b>
    </div>
    

    TS

     compareFn(c1, c2): boolean {
        return c1 && c2 && c1.CountryName === c2.CountryName ;
      }
    

    例如:https://stackblitz.com/edit/angular-8x8hkc

    【讨论】:

    • 谢谢,我将其标记为答案。但我认为这种方法会影响向下列表具有 100 个或更多项目的性能。我测试了 5 个项目。对于设置默认值,它调用 CompareWith 函数 15 次!...所以我的事情是下拉项目增加性能下降。有没有动态的方法
    【解决方案2】:

    我认为原因是,虽然这些对象具有相同的值,但其中一个不=== 另一个,因为它们是单独的实例。

    相反,你可以这样做

     this.SelectedCountry3 = this.countryList[1];
    

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 1970-01-01
      • 1970-01-01
      • 2017-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      相关资源
      最近更新 更多