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

The step-by-step guide on implementing secure authentication using cookies in Next.js

I am encountering a minor issue. I am still very new to Nextjs and I am attempting to learn by creating an app. I have successfully implemented a Login system using Next, but I am facing some challenges in securing routes. After a successful login, I have ...

Does the ES6 specification include .finally()?

Many Promise libraries such as Q or Bluebird have a method called .finally that is executed on both success and error. Does the ES6 promise also include this method? I haven't been able to find it. It doesn't seem to be present in Babel (6to5). ...

Unable to transfer the variable name between different node modules for the purpose of using it as a chat room identifier in a socket.io application

Users are able to provide a room name, however when using module.exports in a separate file to retrieve it, the value shows as undefined. This issue likely arises from the asynchronous nature of the process. //roomcheck.js var nsp = io.of("/gameroom"); n ...

How should we structure our JavaScript code: MVC or self-rendering components?

I'm in the process of developing a highly JS-centric web application. The bulk of the work is being carried out on the client side, with occasional syncing to the server using AJAX and XMPP. This is my first venture into creating something of this ma ...

Launching the VS Code debugger feels like inviting my web app to a party

Recently, I've noticed an issue while debugging my vs code. It appears that the debugger hosts my app without me even running npm start. This behavior allows me to access my app in Chrome without initiating npm start. Normally, my app runs on port 300 ...

Finding the Perfect Placement for an Element in Relation to its Companion

Is there a way to achieve an effect similar to Position Relative in CSS using jQuery? I have developed a tooltip that I want to attach to various objects like textboxes, checkboxes, and other text elements. My code looks something like this: <input i ...

Concealing applicationId and clientToken in Datadog

I'm currently using an Angular application and I've integrated it with the Datadog application to utilize Session and Replay (RUM). However, I am concerned about the security of my sensitive information such as applicationId and clientToken. Is t ...

How can I utilize passed in parameters in Meteor React?

I am trying to figure out how to use two params that I have passed in the following example. Can someone please assist me? updater(layer, item){ this.setState({layer5: <img id="layer5" className="on-top img-responsive center-block" name="layer5" ...

Setting up an Angular proxy for Server prod: A step-by-step guide

Exploring a new approach in my Angular front end app, I aim to conceal the API URL from the browser's network. For example, instead of directly calling api.url.dz/login, I wish to call front.url.dz/login on the front end and then redirect it to api.ur ...

Monitor the fullscreenChange event with angularJs

Utilizing a button to activate fullscreen mode for a DOM element using the fullscreen API is functioning correctly. The challenge arises when exiting fullscreen mode, requiring the listening for the fullscreen change event in order to resize the DOM elemen ...

I am experiencing issues with md-no-focus-style not functioning correctly in my configuration

I have a button that triggers the opening of my navigation bar: https://i.sstatic.net/nMr0i.jpg When I click on it, a hitmarker appears: https://i.sstatic.net/OLQaE.jpg The issue is that even after clicking on a navigation item and transitioning to the ...

Removing a post in Meteor-React using a submission modal is not possible as the post is not defined

After creating an additional submit modal for user confirmation when deleting a post from the collection, I'm facing difficulty in targeting the post. I also have a productivity query - should I include the DeletePost component in each post component ...

What is the best way to show static files from the backend in a React application?

Currently, my setup involves a React application connected to an Express-Node.js backend through a proxy. Within the backend, there are some static files in a specific directory. When I make requests and embed the response link in the "src" attribute of an ...

Can you explain the variance between using 'npm i' and 'npm install'?

Can you explain the distinction between running npm i and npm install? Both commands are used to install all node Modules listed in the package.json file. While the purpose of both commands is clear - to install modules, there may be subtle differences be ...

Redux-form fails to retrieve the value of the SelectField

I'm trying to work with a simple form using react and redux-form. My goal is to gather all the field values from my form and send them to my RESTful API using jQuery ajax. Unfortunately, I've run into an issue where redux-form doesn't seem ...

Dealing with a Node and Express server can be tricky, especially when trying to proxy a POST request along with parameters. You might encounter the error

I am trying to forward all requests made to /api/ from my local node server to a remote server, while also adding some authentication parameters to them. Everything works smoothly for GET requests with query parameters and POST requests without specifying ...

Dynamic stacking of buttons in response to user navigation choices

Is it possible to create a navigation bar with 5 buttons using CSS and JS? Here is what I am looking to achieve: Display 5 nav/button options When a user clicks on a button, the other buttons should transition or hide, leaving only the selected button vi ...

Is it possible to direct users to varying links based on their individual status?

import React from "react"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import Link from "next/link"; import { cn } from "@/lib/utils"; import { FaCircleChec ...

The printing code is not able to interpret the CSS

Having trouble with this script not reading the style properly when printing, can anyone assist in identifying the issue? <script type="text/javascript"> $(function () { $("#btnPrint").click(function () { var contents = $( ...

What is the reason for adding CSS styles to a JavaScript file without importing them?

/Navbar.js/ import './navbar.scss'; import {FaBars, FaSearch} from "react-icons/fa"; import { useState } from 'react'; function Navbar(){ const [hide,sethide] = useState(true); const barIcon = document.querySelectorAl ...