【问题标题】:Angular2 [selected] does not work to set up the default value?Angular2 [selected] 设置默认值不起作用?
【发布时间】:2017-11-18 22:54:24
【问题描述】:

我正在尝试为我的选择设置默认值,所以我尝试了

[selected]= "selected_choice == 'one'"

类似的东西

但这没有用。

人们说 [selected] 不再有效,所以我也尝试了 [attr.selected] 但效果不佳..

这是我的一个选择标签的全部代码

  <select (change)="passValue3()" formControlName="school" class="form-control" required [(ngModel)]="selected_student" class="selectionbox">
    <option *ngIf="selected_student == undefined">학년 선택</option>
    <option *ngFor="let gradetype of gradeTypes" [ngValue]="gradetype" [attr.selected] = "gradetype.gradeType === 'Middle'">{{gradetype.gradeName}}</option>
</select>

如何设置选择的默认选项?

【问题讨论】:

标签: angular select binding


【解决方案1】:

你需要做这样的事情:

在标记中:

<select placeholder="Sample select" [(ngModel)]="selectedItem">
                    <option [value]="'all'">View All</option>
                    <option [value]="'item-1'">Item-1</option>
                    <option [value]="'item-2'">Item-2</option>
                </select>

在组件中

  selectedItem='all'

【讨论】:

  • 为我工作。谢谢。
【解决方案2】:

您比较通过compareWith 属性选择的选项,如果您使用的是角度4,它可能不适用于角度2。

HTML 文件:

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">  
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS 文件

byAnimal(item1,item2){
  return item1.type == item2.type;
}

link 的最佳解决方案之一

【讨论】:

    【解决方案3】:

    这是我的解决方案:

    示例是关于时区的。从后端我得到了下一个对象项:

    activeItem = { "timezone": { "timeZoneHolder": "Europe", "region": "Europe/Paris (CEST)", "UTC": "UTC+1"  }}
    

    随着来源的变化,我模型中的同一个项目看起来有点不同:

    { "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }
    

    正如你看到的有点不同。

    这是我的模型:

    timeZones = [{ "timeZoneHolder": "France", "region": "Europe/Paris", "UTC": "UTC +01:00" }, { "timeZoneHolder": "French Polynesia", "region": "Pacific/Gambier", "UTC": "UTC -09:00" }]
    

    这里是选择的标记,就像一个魅力:

    <select id="timezone" name="timezone" [(ngModel)]="activeItem.timezone">
    <option [ngValue]="activeItem.timezone" [selected]="true" disabled hidden>{{activeItem.timezone.region}}</option>
    <option *ngFor="let timeZone of timeZones"
            [ngValue]="{timeZoneHolder: timeZone.countryName, region: timeZone.timeZone, UTC: timeZone.UTC}">
        {{timeZone.timeZone}}
    </option>
    

    享受:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-03
      • 2019-08-22
      • 2016-04-25
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多