选择选项中的Angular 4更新列表

时间:2018-08-16 13:15:23

标签: angular typescript

<select [(ngModel)]="yearSelected" id="year" (click)="filterYear()">
    <option value="" disabled selected>Year</option>
    <option *ngFor="let y of yearsUnique" [value]="y">{{y}}</option>
</select>
<select [(ngModel)]="facultySelected" id="faculty" (click)="filterFaculty()">
    <option value="" disabled selected>Faculty</option>
    <option *ngFor="let f of facultiesUnique" [value]="f">{{f}}</option>
</select>

用户选择了一年之后,在我的TypeScript类中,我用同年的学院更新 facultiesUnique 列表(在初始加载时,它会加载所有学院):

filterYear() {

    setTimeout(() => {
      console.log("this.yearSelected " + this.yearSelected);

      this.filterList = this.courseList.filter((course: CourseModel) =>
        (course.Year.toString().indexOf(this.yearSelected.toString()) !== -1));

      this.facultiesUnique = this.courseList.filter((course: CourseModel) =>
        (course.Year.toString().indexOf(this.yearSelected.toString()) !== -1));
      this.facultiesUnique = this.courseList.map(data => data.Faculty);

    }, 500);

,但不会使用相关列表更新下拉列表。 关于如何做的任何想法? 谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用

(ngModelChange)="filterFaculty()" 

(change)="filterFaculty()"

然后在filterFaculty()函数中,您可以获取所选值,并将其存储在以下位置:

this.facultySelected

答案 1 :(得分:0)

您可以使用(change)="filterYear($event.target.value)"代替(click)="filterYear()"

我已在 Stackblitz

上创建了一个演示
  

component.html

<select [(ngModel)]="yearSelected" (change)="filterYear($event.target.value)">
    <option value="" disabled selected>Year</option>
    <option *ngFor="let y of yearsUnique" [value]="y">{{y}}</option>
</select>
<select [(ngModel)]="facultySelected"  (change)="filterFaculty($event.target.value)">
    <option value="" disabled selected>Faculty</option>
    <option *ngFor="let f of facultiesUnique" [value]="f.name">{{f.name}}</option>
</select>
  

component.ts

get facultiesUnique() {
    return this.dummyData.filter(items => {
      return items.year == this.yearSelected
    })
}