使用ngIf表达式可以根据选择选项值有条件地显示元素



我正在尝试使用下拉选择来有条件地显示不同的元素。因此,当选择一个选项时,会根据下拉列表中的值为DOM提供一个不同的组件实例。

我不确定是否正确绑定了带有*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'}
]

您可以尝试使用以下方法:在.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>

In.ts文件

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

//功能

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

最新更新