我正在学习Angular,想知道如何仅当用户在下拉列表中选择特定项目时才能隐藏某些项目并显示某些项目。
例如,在我的页面中,我具有图表文本框,文本文本框,网格文本框以及包含图表,文本和网格的下拉列表。当用户选择“文本”时,我只想显示“文本”文本框并隐藏其余部分。
现在,当我运行该项目时,三个图表类型选项都会显示在下拉列表中,但是当我选择“文本”并且在ngIf上出现错误时,它什么也没做
“属性'文本'在'ChartType'类型上不存在。”
如果有人能教我或帮助我,我将非常感激。
我遇到的问题是我从github找到的项目,下拉列表的数据在另一个文件chart.model.ts中,它的写法是这样的
export class ChartUtil {
public static getChartTypeDisplay(type: ChartType): string {
switch (type) {
case ChartType.chart:
return "Chart"
case ChartType.text:
return "Text";
case ChartType.grid:
return "Grid";
default:
return "unknown";
}
}
}
并像这样显示它
design.component.ts
chartTypes: TypeListItem[] = [];
setupTypes() {
let keys = Object.keys(ChartType);
for (let i = 0; i < (keys.length / 2); i++) {
this.chartTypes.push({ value: parseInt(keys[i]), display: ChartUtil.getChartTypeDisplay(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从这些文件中上传了所有代码
我不知道这是否是您想要的,因为您没有在代码中包含下拉列表。该解决方案将使用带有想要的ChartTypes的Enum呈现一个下拉列表。
组件:
import { Component, OnInit } from '@angular/core';
export enum ChartTypes {
Chart = 'Chart',
Text = 'Text',
Grid = 'Grid',
}
@Component({
selector: 'app-select-by-type',
templateUrl: './select-by-type.component.html',
styleUrls: ['./select-by-type.component.css']
})
export class SelectByTypeComponent implements OnInit {
// create an enum variable to work with on the view
chartTypes = ChartTypes;
// initialize the dropdown to a default value (in this case it's Chart)
chartsValue: string = ChartTypes.Chart;
constructor() { }
ngOnInit() {
}
}
视图:
<select
[(ngModel)]="chartsValue"
style="width: 100%; height: 40px; line-height: 40px; text-align: center; background-color: #eaeaea; color: #333"
>
<option
*ngFor="let chartType of chartTypes | keyvalue"
[value]="chartType.value"
>
{{ chartType.value }}
</option>
</select>
<div style="width: 100%; height: 40px; line-height: 40px; text-align: center; background-color: #333; color: #eaeaea">
<div *ngIf="chartsValue === chartTypes.Chart">
Chart
</div>
<div *ngIf="chartsValue === chartTypes.Text">
Text
</div>
<div *ngIf="chartsValue === chartTypes.Grid">
Grid
</div>
</div>