首页 > 解决方案 > 如何使用 API 中的数据在离子选择中设置条件默认值

问题描述

我是 angular 7 和 Ionic 4 的新手。

我正在开发一个移动应用程序,我正在使用一个 API,我有一个任务列表,当我点击一个任务时,一个模式打开,显示任务信息,在这个模式中有一些字段是元素,例如分配的用户,我想根据创建任务时选择的分配用户来设置离子选择默认值。

总而言之,我希望如果分配了一个用户,当模态出现时,它将在离子选择中设置为默认值。

HTML 文件:

<ion-row>
  <ion-col>
    <ion-label>Asigned User:</ion-label>
    <ion-select placeholder="Asigned User" formControlName="assignedUserId" > 
      <ion-select-option *ngFor="let user of simpleUsers|async;" [value]="user.id" (ionChange)="setUser(user.id)">
        {{user.lastName}} {{user.firstName}}
      </ion-select-option>
    </ion-select>
  </ion-col>
</ion-row>

TS 文件:

this.taskForm = this.formBuilder.group({
  'title':[null],
  'description' : [null],
  'descriptionHtml':[null],
  'assignedUserId': [null],
  'deadline':[null],
  'deadlineType':[null],
  'fromDate':[null],
  'clientId':[null]
});

// ...

async getTaskInfo() {
  this.taskId = this.navParams.get('taskId');

  await this.api.getTaskById(this.taskId).subscribe(result => {
    this.task = result;
  });
}

async getCompanies() {
  this.clients = this.api.getCompanies();
}

async getSimpleUsers() {
  this.simpleUsers = this.api.getSimpleUsers();
}

async setUser(userId) {
  this.assignedUserId = userId;
}

async setClient(clientId) {
  this.clientId = clientId;
}

标签: typescriptangular7ionic4

解决方案


由于您将 绑定ion-selectassignedUserId控件并且将[value]属性从ion-select-option点绑定到 ,因此您user.Id似乎唯一需要做的ion-select就是assignedUserId初始化. 它会是这样的:

// ...

async getTaskInfo() {

  this.taskId = this.navParams.get('taskId');

  // If you want to use await, getTaskById() should return a promise
  this.task = await this.api.getTaskById(this.taskId).toPromise();

  // I'm assuming the task has an userId property
  if(this.task && this.task.userId) {

    // Update the value of the control
    this.taskForm.get('assignedUserId').setValue(this.task.userId);    

  }

}

// ...

推荐阅读