我有一个学生及其选择的课程列表。现在有一个下拉菜单,其中显示了课程列表,通过从下拉菜单中选择一个课程,可以显示选择了特定课程的学生列表。 在.ts
allStudents : Student[]=[
{name:'James',course:'Angular'},
{name:'Kary',course:'Android'},
{name:'Bob',course:'Java'},
{name:'Pam',course:'Java'},
{name:'Steve',course:'Angular'},
{name:'Williams',course:'Android'},
{name:'Julis',course:'Angular'},
{name:'Matt',course:'Java'},
{name:'Willy',course:'Android'},
];
以HTML
<div class="container">
<div class="row">
<div class="col-4">
<select class="form-control" [(ngModel)]="crse" (keyup)="show()">
<option value=''>Courses...</option>
<option value="ang">Angular</option>
<option value="and">Android</option>
<option value="java">Java</option>
</select>
</div>
<div class="col-4 bg-dark text-light">Name</div>
<div class="col-4 bg-dark text-light">Course</div>
<div class="row" *ngFor="let st of showStudents">
<div class="col-4 border">{{st.name}}</div>
<div class="col-4 border">{{st.course}}</div>
</div></div></div>
需要使用过滤器执行此操作。
答案 0 :(得分:2)
let arr=[
{name:'James',course:'Angular'},
{name:'Kary',course:'Android'},
{name:'Bob',course:'Java'},
{name:'Pam',course:'Java'},
{name:'Steve',course:'Angular'},
{name:'Williams',course:'Android'},
{name:'Julis',course:'Angular'},
{name:'Matt',course:'Java'},
{name:'Willy',course:'Android'},
];
var course="Angular";
let newar = arr.filter(res => res.course === course);
console.log(newar)
if(this.crse === 'ang'){
this.crse='Angular';
}else if(this.crse === 'and'){
this.crse='Android';
}
else if(this.crse === 'java'){
this.crse='Java';
}
this.showStudents= this.allStudents.filter(res => res.course === this.crse);
最好将选项值分配为完整的课程名称,以减少初始名称的检查。
答案 1 :(得分:0)
我已将keyup
更改为(ngModelChange)="show(crse)"
HTML:
<select class="form-control" [(ngModel)]="crse" (ngModelChange)="show(crse)">
<option value=''>Courses...</option>
<option value="ang">Angular</option>
<option value="and">Android</option>
<option value="java">Java</option>
</select>
在 TS:中,用过滤器,
编写了新功能show(crse)
show(crse) {
let char = crse.charAt(0).toUpperCase() + crse.substr(1);
let tempArray = [];
this.allStudents.filter(function(x) {
if(x.course.startsWith(char) === true) {
tempArray.push(x);
}
});
this.showStudents = tempArray;
}