[英]how to use ngif properly in Angular
我在 github 上找到了 angular 项目,我试图继续研究它以便我可以学习,但我一直坚持如何正确使用 ngIf。
所以我在 chart.model.ts 文件中有我的三种图表类型,我不确定谁可以访问我的 design.component.ts 文件中的数据,以便我可以使文本框仅在用户 select 文本打开时显示下拉列表。
现在,当我运行项目但没有做任何事情时,三个图表类型选项显示在下拉列表中,而且我的 ngIf 出现错误说
“‘ChartType’类型上不存在属性‘文本’。”
如果有人可以教我或帮助我,我将不胜感激。
图.model.ts
export class ChartUtil {
public static getChartTypeDisplay(type: ChartType): string {
switch (type) {
case ChartType.chart:
return "Charts";
case ChartType.text:
return "Text";
case ChartType.grid:
return "Grid";
default:
return "unknown";
}
}
export enum ChartType {
chart = 1,
text,
grid
}
}
设计.component.ts
import { ChartType } from 'src/app/chart.model';
chartTypes: ChartType;
setupTypes() {
keys = Object.keys(ChartDataType);
for (let i = 0; i < (keys.length / 2); i++) {
this.dataTypes.push({ value: parseInt(keys[i]), display: ChartUtil.getChartDataTypeDisplay(parseInt(keys[i])) })
}
}
设计.组件.html
<ng-container *ngIf="chart.chartTypes == chartTypes.text">
<mat-form-field appearance="fill">
<mat-label>Text</mat-label>
<input matInput />
</mat-form-field>
我无法在 stackblitz 上上传完整的项目,但我通过https://stackblitz.com/edit/angular-ivy-dmf3vn上传了这些文件中的所有代码
ng-If 的工作原理是,如果条件为真,则在 ng-if 中编写的代码将在 HTML 中呈现/显示。 如果条件为假,则不会渲染/显示代码。 因此,根据您的条件将值设置为 true 或 false。
<ng-container *ngIf="displayChartInfo">
<mat-form-field appearance="fill">
<mat-label>Text</mat-label>
<input matInput />
</mat-form-field>
在你的 ts 中,
displayChartInfo:boolean = false;
public static getChartTypeDisplay(type: ChartType): string {
switch (type) {
case ChartType.chart:
this.displayChartInfo =true;;
break;
case ChartType.text:
this.displayChartInfo =true;;
break;
case ChartType.grid:
this.displayChartInfo =true;;
break;
default:
this.displayChartInfo =false;;
break;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.