Struggle with implementing enums correctly in ngSwitch

Within my application, I have implemented three buttons that each display a different list. To control which list is presented using Angular's ngSwitch, I decided to incorporate enums. However, I encountered an error in the process.

The TypeScript code snippet looks like this:

export enum ListType {People, Cars}

export class AppCmp implements OnInit {

    listOfPeople: Person[];
    listOfCars: Car[];

    currentListView: CurrentListView;

    constructor(private _MyService: MyService) {
    };


    public setListType(type: ListType) {
        this.listType = type;
    }

    ngOnInit() {
      this._MyService.getListOfPeopleData().subscribe(res => {
        this.listOfPeople = res;
      });

      this._MyService.getListOfCarsData().subscribe(res => {
        this.listOfCars = res;
      });
    }
}

This is the HTML code section:

<div>
  <button md-button
          (click)="setListType(listType.People)"
          class="md-primary">People
  </button>

  <button md-button
          (click)="setListType(listType.Cars)"
          class="md-primary">Cars
  </button>
</div>


<md-content>

  <h1 align="center">{{title}}</h1>

  <div [ngSwitch]="currentListView">

    <div *ngSwitchCase="listType.People">
        <div class="list-bg" *ngFor="#person of listOfPeople">
          ID: {{person.id}} <p></p> name:{{person.name}}
        </div>
      </div>
    </div>
    <div *ngSwitchCase="listType.Cars">
        <div class="list-bg" *ngFor="#car of listOfCars;>
          ID: {{car.id}} <p></p> color: {{car.color}}
        </div>
    </div>

  </div>

</md-content>

I'm encountering difficulty with this setup. Can anyone point out where I am going wrong?

The specific error message reads as follows:

EXCEPTION: Error: Uncaught (in promise): Template parse errors: Can't
bind to 'ngSwitchCase' since it isn't a known native property ("  
  <div [ngSwitch]="currentListView">

     <div [ERROR ->]*ngSwitchCase="listType.People"> Property binding ngSwitchCase not used
by any directive on an embedded template ("  
  <div [ngSwitch]="currentListView">

I am utilizing Typescript and Angular2 for this project.

Answer №1

When working with the enum:

export enum ListType {People, Cars}

To incorporate it into your template, for example:

...
<div *ngSwitchCase="listType.People">
...

You need to ensure that the enum is accessible within your component by creating a property in your class that will serve as an "alias" (in the template) for the enum, like so:

export class AppCmp implements OnInit {

  public listType = ListType;  // <-- a property with the desired name for the enum
...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtain an Angular2/4 Carousel component through a service in order to create a seamless loop

I am currently working on implementing a carousel in Angular. While it is not complicated to include slide images directly in the html, I am interested in fetching them from an array stored in a service for more dynamic functionality. Here is a snippet of ...

Angular Material datetime picker with an option for transparent background

After upgrading my angular from version 15 to 16, I encountered a strange issue with the material date time picker. The GUI part of the picker appeared half transparent as shown in this image: Has anyone else faced this kind of problem with the material d ...

What is the process for deploying a .NET Core + Angular single page application to multiple environments?

After utilizing the Angular project template with ASP.NET Core in Visual Studio 2019, I developed an application that includes multiple environments: DEV, STG, and Production. Each environment corresponds to specific "appsettings.json" files for the .NET p ...

Seamless Navigation with Bootstrap Navbar and SmoothScroll

Currently, I have a custom-built navbar that functions perfectly, with full mobile responsiveness. However, I am facing an issue with the nav-item's (headings). The nav-item's direct users to different sections of the same page using #. I have i ...

Having trouble converting svg to png, thinking it might be due to discrepancies in svg elements

I am facing a puzzling issue where two different SVG elements are causing my JavaScript to work in one scenario but not the other. I have replaced the SVG elements in both examples, and surprisingly, only one works while the other does not. You can view th ...

Dealing with numerous Ajax calls within a single Ajax request

I am utilizing the $http method in angularjs to retrieve multiple "parent" elements. Within the success method of these Ajax calls, I need to loop through the parent elements and make another Ajax call for each parent element to fetch its corresponding chi ...

What is the best way to convert items from a foreach loop into a JSON string using the json_encode() function in PHP?

I want to populate a string with all the emails fetched from the database, in order to use JavaScript for checking if the email entered by a user in a form field is already registered. I'm attempting to utilize the json_encode() function. $connec ...

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

The URL for the dynamic import in Workbox is loading incorrectly

For my laravel/vuejs application, I am utilizing workbox and babel dynamic imports. Additionally, I am making use of the laravel-mix and laravel-mix-workbox plugin to compile and generate service worker via generateSW(). The assets load correctly on the r ...

Stop the scrolling behavior from passing from one element to the window

I am facing an issue with a modal box window that contains an iframe. Inside the iframe, there is a scrollable div element. Whenever I try to scroll the inner div of the iframe and it reaches either the top or bottom limit, the browser window itself start ...

Is it possible to generate a Token in Nexus for private packages without using the UI interface?

We have implemented Sonatype Nexus Repository ManagerOSS 3.29.0-02 and are currently facing an issue in generating a TOKEN that can be used with .npmrc following this specific structure: registry=http://NEXUS-IP:8081/repository/GROUP-NAME http://NEXUS-IP:8 ...

Concealing bootstrap-styled dropdowns within ng-grid

Currently, I am in the process of enhancing a table form. Within each row of the table, there are various elements, including two drop-downs in specific columns for every row. I decided to upgrade the table to ng-grid and transform the plain select widgets ...

Accessing the media player of your system while developing a VSCode extension using a nodejs backend: A comprehensive guide

I am currently utilizing the play-sound library in my project. I have experimented with two different code snippets, each resulting in a unique outcome, none of which are successful. When I implement const player = require('play-sound')({player: ...

Defining the active element in the menu using JavaScript

I need help with my navigation menu: <ul> <li id="active"><a href="/">Home</a></li> <li><a href="/about/">About Us</a></li> <li><a href="/services/">Our Services</a>< ...

Switch up the Javascript popup code without any specific pattern

I am looking to add variety to my pop up ads on my website by randomly changing the Javascript code for each ad every time a page is loaded. How can I achieve this? Script 1 <script type="text/javascript"> var uid = '12946'; var w ...

How to Target HTML Tags Locally using CSS Modules in Next.js?

I am looking to implement smooth scrolling specifically on one page in my Next.js application, such as my blog. Instead of applying it to the entire site through the globals.css file, I need a way to inject scroll-behavior: smooth; into the html tag only f ...

Unable to locate module: Unable to locate the file './Header.module.scss' in '/vercel/path0/components/Header'

I encountered an error while attempting to deploy my next application on Vercel. I have thoroughly reviewed my imports, but I am unable to pinpoint the issue. Module not found: Can't resolve './Header.module.scss' in '/vercel/path0/comp ...

Difficulty encountered when applying date filtering on a specific filter in the MUI-DataGrid

Software Version: "@mui/x-data-grid": "^6.2.1" I have a script that generates columns for the DataGrid as shown below (only including relevant code) if (prop === "date" || prop === "dateModified" || prop === "n ...

Enhance your web form with the Bootstrap 4 tags input feature that allows users to add tags exclusively

I'm currently utilizing Bootstrap 4 along with Bootstrap Tags Input to create a multiple category selection feature. My goal is to enable users to choose multiple items exclusively from the predefined categories listed in the predefined_list. At pres ...

"Encountering issues with npm failing to install node_modules

When attempting to install Angular using npm, I noticed that it is not creating a node_modules directory. This issue occured while following the steps shown in the screenshot below: MacBook-Pro-di-Sandro:~ sandropalmieri$ cd Documents/mycode/ MacBook-Pr ...