1

我刚刚在 ionic 版本 6 中创建了一个离子选择。我的问题是我已经成功地在页面加载时预先选择了一个值,但是这个预先选择的值没有显示在 UI 中?!

它只是在我单击选择之后出现,但在它不出现之前(如图 2 所示)。我在 ionViewWillEnter 方法中加载数据并使用 NgModel 预先选择它!

在这里你可以看到它:

页面加载时的样子

当我打开选择时看起来像这样(预选择值成功

选择的 HTML 代码

    <ion-row>
  <ion-col>
    <ion-item lines="inset">
      <ion-label hidden>Abteilungen wählen</ion-label>
      <ion-select (ionChange)="loadOpenTicketsForDepts()" style="min-width: 100%"
        placeholder="Abteilungen wählen..." multiple [(ngModel)]="selectedDepartments" cancelText="Abbruch"
        okText="OK">
        <ion-select-option value="{{dept.id}}" *ngFor="let dept of departments">
          {{dept.name}}
        </ion-select-option>
      </ion-select>
    </ion-item>
  </ion-col>
</ion-row>

打字稿数据加载:

  ionViewWillEnter(): void {
//1. get department where logged in emp is working in
this.authService.getPersNr().then((res) => {
  //now load dept
  this.ticketService.getEmployeeByName(res).subscribe(emp => {

    const costcenter = emp.costcentreId;

    this.costCentreService.getDepartmentById(costcenter).subscribe(dept => {
      //add to selected departments if it is not already in
      if (this.selectedDepartments.includes(String(dept.id)) == false) {
        this.selectedDepartments.push(String(dept.id))
      }
      //now load tickets for all selected departments
      this.loadOpenTicketsForDepts();
    })
  })
})

this.costCentreService.getDepartments().subscribe(res => {
  this.departments = res;
})

}

4

1 回答 1

0

添加对名为#departmentSelector 的选择器的引用:

 <ion-select #departmentSelector (ionChange)="loadOpenTicketsForDepts()" style="min-width: 100%"
    placeholder="Abteilungen wählen..." multiple [(ngModel)]="selectedDepartments" cancelText="Abbruch"
    okText="OK">
    <ion-select-option value="{{dept.id}}" *ngFor="let dept of departments">
      {{dept.name}}
    </ion-select-option>
  </ion-select>

然后你可以在视图加载后从你的打字稿类访问它:

声明您的参考:

  @ViewChild("departmentSelector") departmentSelector!: IonSelect;

然后您可以在视图完全加载时访问它:

ngAfterViewInit(){


//your async function ...

this.authService.getPersNr().then((res) => {
  //now load dept
  this.ticketService.getEmployeeByName(res).subscribe(emp => {

    const costcenter = emp.costcentreId;

    this.costCentreService.getDepartmentById(costcenter).subscribe(dept => {
      //add to selected departments if it is not already in
      if (this.selectedDepartments.includes(String(dept.id)) == false) {
       // this.selectedDepartments.push(String(dept.id))

this.departmentSelector.value = String(dept.id);
   
   }
      //now load tickets for all selected departments
      this.loadOpenTicketsForDepts();
    })
  })
})


//


}
于 2022-01-14T19:23:00.373 回答