[英]How to populate a dropdown based on the value selected in another dropdown?
[英]How to populate the data getting from loop ngFor on select a dropdown based on selected value
我有一个 div 和选择框。 最初,我使用 ngFor 循环填充 div 上的所有数据。 现在我还需要根据选择框中的选定选项填充数据。 假设我选择的值为0,所有匹配到0的数据,需要填充。 我已经在 select 上使用过滤器获取数据,但是如何再次使用相同的变量(partnerContent)在 html 中填充,我没有得到。 这是下面的代码https://stackblitz.com/edit/angular-6b8szk?file=src%2Fapp%2Fapp.component.html
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
partnerContent: any;
selectValChange;
ngOnInit(): void {
this.partnerContent = [
{
id: 1,
status: 'one',
type: 0
},
{
id: 2,
status: 'two',
type: 0
},
{
id: 3,
status: 'three',
type: 1
}
];
}
name = 'Angular';
selected(selectedLevel: any) {
console.log(selectedLevel);
this.selectValChange = this.partnerContent.filter(function(el: any) {
return el.type == selectedLevel.type;
});
console.log(this.selectValChange);
}
}
<hello name="{{ name }}"></hello>
<p>
Start editing to see some magic happen :)
</p>
<div *ngFor="let cont of partnerContent">{{cont.status}}</div>
<select [(ngModel)]="selectedLevel" (change)="selected(selectedLevel)">
<option *ngFor="let content of partnerContent" [ngValue]="content">
{{content.type}}
</option>
</select>
如果我正确理解你的问题。
filteredPartnerContent: any[];
div 总是绑定到这个“过滤”列表
<div *ngFor="let cont of filteredPartnerContent">{{cont.status}}</div>
最初它将等于ngOnInit
this.filteredPartnerContent = [...this.partnerContent];
当下拉值改变时:
this.filteredPartnerContent = this.partnerContent.filter(function(el: any) {
更新
要从下拉列表中删除重复项,首先只获取类型。 这将导致 [0, 0, 1] 的数组
const types = this.partnerContent.map(x => x.type);
下一个过滤掉重复项,这个有很多方法是“单行”
this.uniqueTypes = Array.from(new Set(types));
在 HTML 模板中:
<option *ngFor="let type of uniqueTypes" [ngValue]="type">
{{type}}
</option>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.