I'm learning Angular and wondering how I can't hide some item and show certain items only when the user select specific item in the drop down list.
For example, In my page, I have Chart TextBox, Text TextBox, Grid TextBox and a drop down list that contain Chart, Text, and Grid. when ever user select Text, I want to show only Text TextBox and hide the rest.
right now, the three chart type options are showing on drop drop list when ever I run the project but it's not doing anything when I select Text and also I got an error on my ngIf saying that
"Property 'text' does not exist on type 'ChartType'."
I would be really appreciate if can somebody teach me or help me.
The problem I have is in the project I found from from github, the data for drop down list is in the another file called chart.model.ts and it written like this
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";
}
}
}
and display it like this
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>
I can't uploaded the full project on stackblitz but I uploaded all the code from those file over https://stackblitz.com/edit/angular-ivy-dmf3vn
This is normally how you would tackle a ng-switch
Component Code (badly done)
import { Component, VERSION, OnInit } from '@angular/core';
export class ChartType {
chart = 1;
text = 2;
grid = 3;
}
export class TypeListItem {
public value = 0;
public display = '';
public chartType = -1;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
public chartTypesEnum = new ChartType();
public chartTypes: TypeListItem[] = [];
ngOnInit() {
let keys = Object.keys(this.chartTypesEnum);
for (let i = 0; i < (keys.length ); i++) {
this.chartTypes.push(
{
value: parseInt(ChartType[keys[i]]),
chartType: this.chartTypesEnum[keys[i]],
display: `This is a ${keys[i]}`
})
}
}
}
HTML (again badly done but simple)
<ng-container *ngFor="let chart of chartTypes">
<ng-container [ngSwitch]="chart.chartType" >
<div *ngSwitchCase="chartTypesEnum.chart">Chart</div>
<div *ngSwitchCase="chartTypesEnum.grid">Grid</div>
<div *ngSwitchCase="chartTypesEnum.text">Text</div>
</ng-container>
</ng-container>
Example
https://stackblitz.com/edit/angular-ivy-bievwr
Example 2