首页 > 解决方案 > 使用 ngIf 表达式根据选择选项值有条件地显示元素

问题描述

我正在尝试使用下拉选择来有条件地显示不同的元素。So when an option is selected, the DOM is given a different instance of a component based on the value from the dropdown.

我不确定我是否正确绑定了具有 *ngIf 的 div。

<!--Component.html-->
<mat-form-field>
<mat-select [(ngModel)]="options">
<mat-option *ngFor="let opt of options" [value]="opt.value">
{{opt.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>

<div [(ngModel)]="options" *ngIf="options.value === '2';">
<component-with-table></component-with-table>
</div>
// Component.ts

options = [
{value: '1', viewValue: 'example string'},
{value: '2', viewValue: 'another example string'}
]

标签: angularangular-material

解决方案


您可以尝试使用以下内容:在 .html 文件中

<mat-form-field>
<mat-select (selectionChange)="ChangeOption($event)">
<mat-option   *ngFor="let opt of options" [value]="opt.value">
{{opt.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>

<div *ngIf="optionselected == '2'">
<component-with-table></component-with-table>
</div>
<div *ngIf="optionselected == '1'">
<component-with-table></component-with-table>
</div>

在 .ts 文件中

optionselected:string:"";
options = [
{value: '1', viewValue: 'example string'},
{value: '2', viewValue: 'another example string'}
]

//功能

ChangeOption(event)
{
  this.optionselected = event.value;
}

推荐阅读