Angular2选择无法设置默认值

时间:2017-02-02 07:14:03

标签: javascript angular typescript

我的选择部门模板代码如下,

  <div class="form-group">
    <label class="control-label">Location</label>
    <select class="selectpicker" *ngIf="locations" data-style="btn btn-primary btn-round" title="Select A Location" 
    [(ngModel)]="selectedLocation"
    [ngModelOptions]="{standalone: true}">
        <option *ngFor="let loc of locations"
          [ngValue]="loc">
          {{loc.name}}
        </option>
    </select>
    <span *ngIf="!selectedLocation" class="help-block text-danger">
        You must select one Location.
    </span>
  </div>

此代码适用于从服务器获取位置。单击select下拉列表后,我可以设法列出这些位置。

select.ts

private selectedLocation: any = null;

ngOnInit() {
    this.buildForm();
    this.getLocations();
  }

setDefaultTypeAndLocation() {    
    for (let location of this.locations) {
      if (location.name === this.vehicle.location) {
        this.selectedLocation = location;
        break;
      }
    }
  }

  ngOnChanges() {
    console.log(this.vehicle);
    if (this.vehicle.type.key !== '' && this.vehicle.location) {
      this.setDefaultTypeAndLocation();
    }
    this.buildForm();
  }

getLocations() {
    this.locations = this.locationsService.locations;
    if (!this.locations) {
      this.locationsService.list()
        .subscribe(
          data => {
            this.locations = data;
          },
          error => {
            console.log('err in vehicle form getLocations method');
          }
        );
    } else {
    }
  }

单击父组件上的编辑按钮时,相应的vehicle对象将传递给子组件,从而启动ngOnChanges方法。

请参阅此this.setDefaultTypeAndLocation();调用方法setDefaultTypeAndLocation(),该方法用于设置默认位置(this.selectedLocation = location;)。

从这一点开始,我正确更新了this.selectedLocation值。但在View上,我之前设置的位置未显示为默认位置。

1 个答案:

答案 0 :(得分:0)

也许你没有显示所有代码,但我没有看到你曾经调用getLocations()方法。这意味着this.locations将始终为空列表,因此无法设置任何位置。

修改

不要在ngOnInit中初始化您的位置,而是在需要时更改getLocations方法以更新位置。在ngOnInit中初始化无效,因为ngOnChanges被称为ngOnInithttps://angular.io/docs/ts/latest/guide/lifecycle-hooks.html)。

请参阅此代码示例:

  ngOnInit() {
    //do not initialize locations here
  }

  setDefaultTypeAndLocation() {
    //change this.location to this.getLocations()
    for (let location of this.getLocations()) { 
      if (location.name === this.vehicle.location) {
        this.selectedLocation = location;
        break;
      }
    }
  }

  getLocations() {
    // Add this check
    if (this.locations && this.locations.length > 0) return this.locations;

    this.locations = this.locationsService.locations;
    if (!this.locations) {
      this.locationsService.list()
        .subscribe(
        data => {
          this.locations = data;
        },
        error => {
          console.log('err in vehicle form getLocations method');
        }
        );
    } else {
    }
  }