angular - 使用 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'}
]
解决方案
您可以尝试使用以下内容:在 .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;
}
推荐阅读
- javascript - 要显示的 JavaScript在某个日期之后
- sorting - 报告多个值和排序
- pip - 自托管devpi的客户端URL?
- django - 带有数字键的 Django postgres Json 字段
- android - 我正在尝试将 firebase sdk 添加到 android 项目中
- html - 我怎样才能在这个圈子的顶部添加一个选择类型的收音机?
- java - Spring Boot 和 AspectJ——我可以拦截对 java.util.ArrayList.size() 方法的调用吗?
- mysql - Doctrine - QueryBuilder - 在结果中获得最年轻的实体
- c# - 对于每个确认
- r - 使用 miEconAids 的回归输出的替代方案(除了 `stargazer`)