Ionic select:pre selecte 值在单击一次之前是不可见的

Ionic select: pre selecte value is invisible until clicked once

我刚刚在 ionic 版本 6 中创建了一个 ion-select。 我的问题是我在页面加载时成功地预 select 了一个值,但是这个预 select 值没有在 UI?!

中显示

它只是在我单击 select 之后出现,但在此之前它没有出现(如图 2 所示)。我在 ionViewWillEnter 方法中加载数据并使用 NgModel!

预 select 它

你可以在这里看到:

Looks like this when the page was loaded

Looks like this when I open the select (pre select value was succesful

HTML 代码为 select

    <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>

Typescript 数据加载:

  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;
})

}

添加对名为#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>

然后您可以从打字稿访问它 class 查看加载后:

声明您的参考资料:

  @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();
    })
  })
})


//


}