首页 > 解决方案 > 使用下拉列表中的属性值过滤对象数组 - Angular 模板

问题描述

我正在尝试使用属性值过滤对象数组并在下拉列表中显示过滤结果。这是我的 JSON 结构:

var profiles = [{
"name":"Pavan",
"exp": 2,
"subject":"maths"
},
{
"name":"Mark",
"exp": 6,
"subject":"science"
},
{
"name":"sunny",
"exp": 1,
"subject":"maths"
},
{
"name":"Roy",
"exp": 2,
"subject":"science"
}]

在这里,我想在主题为数学的下拉列表中显示名称。我可以在 ts 文件中进行过滤,并且可以在下拉列表中显示,但我想自己在模板中进行过滤部分。现在我用下面的代码显示所有的名字。

<select   name="profile" class="bx--text-input"  [formControl]="profile">   
          <option value=""  selected>Select profile name</option>
        <option [value]="state.name"  *ngFor="let state of profiles">{{state.name}}</option> 
 </select>  

因此,如果我只想显示数学主题,如何在模板文件中进行过滤。

标签: javascripthtmlangular

解决方案


<select   name="profile" class="bx--text-input"  [formControl]="profile">   
          <option value=""  selected>Select profile name</option> 
         <ng-container *ngFor="let state of profiles;">
              <option [value]="state.name" *ngIf="state.subject =='maths'">
                  {{ state.name }}
              </option>
          </ng-container>
 </select>


推荐阅读