【问题标题】:Changing the index in one dropdown needs to set the selected option in another dropdown in angular and typescript更改一个下拉列表中的索引需要在另一个下拉列表中以角度和打字稿设置选定的选项
【发布时间】:2021-08-08 06:59:52
【问题描述】:

我是 Angular 新手,我需要一些帮助来满足以下要求:

我的角度模板中有两个下拉列表,我想要的是,当我在一个下拉列表中更改索引时,应该在另一个下拉列表中选择特定选项(值)。两个下拉菜单都从 API 获取值,并使用双向绑定。

例如,如果第一个下拉列表包含学生姓名,并且我在此下拉列表中选择了另一个选项,那么第二个下拉列表(包含一年级、二年级等类)应该自动为该学生选择,即,如果我选择学生说“约翰”,如果他正在二年级学习,那么下拉菜单 2 应将所选选项设置为二年级。

我这样做的目的:

我在第一个选择选项中使用了(更改)事件,我在第二个下拉列表中获得了我需要的值,但我不确定如何将它分配给第二个下拉列表。

第一个下拉菜单:

 <select
        class="form-control form-control-lg form-control-solid"
        name="studentId"
        [(ngModel)]="model.studentId"
        required
        #studentId="ngModel"
        (change)="getClassByStudent(studentId.value)"
      >
        <option
          *ngFor="let student of studentList"
          value="{{ student .id }}"
        >
          {{ student.studentName}}
        </option>
      </select>

第二个下拉菜单:

<select
        class="form-control form-control-lg form-control-solid"
        name="classId"
        [(ngModel)]="model.classId"
        required
        #classId="ngModel"
      >
        <option
          *ngFor="let class of classList"
          value="{{ class.id }}"
        >
          {{ class.className }}
        </option>
      </select>

TypeScript:

 getClassByStudent(studentId) {
      debugger;
      this.commonService.API_URL = 
      `${environment.apiUrl}/admin/studentClass/${studentId}`;
       this.commonService.getList().subscribe(
       response => {
          this.classAsPerStudent = response?.data;
          this.classId= this.classAsPerStudent.studentId
     });
 }

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我在第一个选择选项中使用了(更改)事件,我在第二个下拉列表中获得了我需要的值,但我不确定如何将其分配给第二个下拉列表,跨度>
  • 你能给我们看一些代码吗?也许使用您目前拥有的最少代码创建一个示例stackblitz
  • @SiddAjmera 请参阅上面的代码,因为我已经编辑了我的问题。

标签: angular typescript dropdown


【解决方案1】:

这个问题缺少很多信息。我仍然尝试复制该场景并解决了问题。

因此,假设您的 CommonService 上的 getList 方法返回的数据如下所示:

{
  "data": {
    "studentId": 5
  }
}

您需要在 subscribe 块中将其设置为 this.model.classId 而不是 this.classId

getClassByStudent(studentId) {
  // ...
  this.commonService.getList().subscribe((response: any) => {
    this.classAsPerStudent = response.data;
    this.model.classId = this.classAsPerStudent.studentId; // <----- HERE
  });
}

第二件事是,第二个select 列表中的所有options 的值都为coaches.id,而应该是class.id

<select
  class="form-control form-control-lg form-control-solid"
  name="classId"
  [(ngModel)]="model.classId"
  required
  #classId="ngModel"
>
  <option
    *ngFor="let class of classList"
    [value]="class.id"
  >
    {{ class.className }}
  </option>
</select>

这是一个 Working Sample Code on StackBlitz 供您参考。

注意:从第一个列表中选择任何学生,并注意第二个选择列表中的选项更改为 Class 5。它只会一直更改为 5 级,因为在我的模拟中,我已将 studentId 硬编码为 5。

【讨论】:

  • 非常感谢。使用 this.model.classId 而不是 this.classId 解决了这个问题。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 2022-01-12
相关资源
最近更新 更多