【问题标题】:assign select initial value in angular4在angular4中分配选择初始值
【发布时间】:2017-10-17 03:58:23
【问题描述】:

在我的角度值中,我可以选择更改时区。 this.userTimeZone 是我组件中的一个对象。

{
AdjustmentRules:null
BaseUtcOffset:"-04:30:00"
DaylightName:"Venezuela Daylight Time"
DisplayName:"(UTC-04:30) Caracas"
Id:"Venezuela Standard Time"
StandardName:"Venezuela Standard Time"
SupportsDaylightSavingTime:false}

我的选择选项如下所示:

<select name="timeZones" [(ngModel)]="userTimeZone" (change)="setTimezoneId($event)" class="form-control">
   <option *ngFor="let time of timezones" [ngValue]="time">{{time.DisplayName}}</option>
</select>

我无法设置选择的初始值。

虽然 userTimeZone 有一个值,但加载时选择显示为空白。

如果我给 userTimeZone.Id 和 [ngValue]="time.id" 该选项会被选中,但更改时返回的值只是 id 而不是整个对象。

I want the entire object when the select option changes ans also set the initial value of the select.

不知道这里出了什么问题。请指导

谢谢

【问题讨论】:

    标签: angular select onchange


    【解决方案1】:

    所以下面是我所做的

     <select name="timeZones" [(ngModel)]="userTimeZone.Id" (change)="setTimezoneId($event)" class="form-control">
          <option *ngFor="let time of timezones" [value]="time.Id"> {{time.DisplayName}} </option>
     </select>
    

    userTimeZone.Id 将与 time.Id 匹配,并选择默认选项。

    在change方法中,我们根据值从json中过滤出对象

        setTimezoneId(event:any) {
                /*Filter object from the json */
                this.userTimeZone = this.timezones.filter(function (zone: any) {
                    return zone.Id == event.target.value;
                })[0];
                console.log(this.userTimeZone);
            }
    

    【讨论】:

      【解决方案2】:

      试试这个:

      使用 (ngModelChange)="setTimezoneId($event)" 代替 (change)="setTimezoneId($event)"

      <select name="timeZones" [(ngModel)]="userTimeZone" (ngModelChange)="setTimezoneId($event)" class="form-control">
         <option *ngFor="let time of timezones" [ngValue]="time">{{time.DisplayName}}</option>
      </select>
      

      【讨论】:

        【解决方案3】:

        您需要在您的选项中使用[attr.value],并确保您的选项的值不是对象,您可以使用和字符串,然后根据需要与集合中的对象匹配。

        在这个例子中检查app.ts

        https://plnkr.co/edit/gvc5bf50sgA57Y0YGRui

        【讨论】:

          猜你喜欢
          • 2011-06-10
          • 1970-01-01
          • 2016-09-17
          • 1970-01-01
          • 2011-06-10
          • 1970-01-01
          • 2012-10-09
          • 2020-04-14
          • 1970-01-01
          相关资源
          最近更新 更多