An easy guide on utilizing ngSwitch for datatype selection in Angular

While working in angular2, I came across a question regarding the usage of ngSwitch to load <div> tag based on the datatype of a variable. Is it possible to achieve something like this:

 <div [ng-switch]="value">
  <p *ng-switch-when="isObject(value)">This is Object</p>
  <p *ng-switch-when="isArray(value)">This is Array</p>
  <p *ng-switch-when="isBoolean(value)">This is Boolean</p>
  <p *ng-switch-when="isNumber(value)">This is Number</p>
  <p *ng-switch-default>This is Simple Text !</p>
</div>

Can we actually load the div tag based on the variable's datatype? If not, are there any potential workarounds for this scenario?

Answer №1

Another option is to implement the use of ngIf:

  <p *ngIf="isObject(value)">This content is an Object</p>
  <p *ngIf="isArray(value)">This content is an Array</p>
  <p *ngIf="isBoolean(value)">This content is a Boolean</p>
  <p *ngIf="isNumber(value)">This content is a Number</p>
  <p *ngIf="!isObject(value) || !isArray(value) || !isBoolean(value) || !isNumber(value)">This content is Simple Text!</p>

Answer №2

Sure, you have the ability to accomplish this task, however, it's best not to do it directly in the template. Instead, create a method in the controller to handle checking for a specific type:

import {Component} from '@angular/core'

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div [ngSwitch]="checkType(name)">
        <p *ngSwitchCase="'string'">is a string!</p>
        <p *ngSwitchDefault>default</p>
      </div>
    </div>
  `,
  directives: []
})
export class App {
  constructor() {
    this.name = 'Angular2 (Release Candidate!)'
  }

  checkType(value) {
    return typeof value
  }
}

Take a look at this working Plunker example.


It is recommended that you update your Angular version to RC first before proceeding with these changes.

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

ConfirmUsername is immutable | TypeScript paired with Jest and Enzyme

Currently, I am experimenting with Jest and Enzyme on my React-TS project to test a small utility function. While working on a JS file within the project, I encountered the following error: "validateUsername" is read-only. Here is the code for the utilit ...

Utilizing Class Types in Generics with TypeScript

Struggling to implement a factory method based on the example from the documentation on Using Class Types in Generics, but hitting roadblocks. Here's a simplified version of what I'm attempting: class Animal { legCount = 4; constructor( ...

Configuring TypeScript to utilize worker_threads

Currently, I am attempting to implement WebWorkers in my Typescript project and I have encountered a hurdle. Despite having installed @types/node and updating everything, 'worker_threads' has transitioned from an experimental feature to a stable ...

Effortlessly passing props between components using React TypeScript 16.8 with the help

In this scenario, the component is loaded as one of the routes. I have defined the type of companyName as a string within the AppProps type and then specified the type to the component using <AppProps>. Later on, I used {companyName} in the HTML rend ...

Incorporating Close, Minimize, and Maximize functionalities into a React-powered Electron Application

Struggling with implementing minimize, maximize, and close functionality for a custom title bar in an electron app using React Typescript for the UI. The issue lies within the React component WindowControlButton.tsx, as it should trigger actions to manipu ...

Steps for modifying the look of a button to display an arrow upon being clicked with CSS

Looking to enhance the visual appearance of a button by having an arrow emerge from it upon clicking, all done through CSS. Currently developing a React application utilizing TypeScript. Upon clicking the next button, the arrow should transition from the ...

Obtain a personalized response from an Angular HTTP service

I'm trying to implement the following code directly in a component: if(exampleService.checkValidityOfToken()) { //do something } Here is the method in exampleService that corresponds to this. I'm not sure if I am returning the value properly or ...

Tips on expanding typings in TypeScript?

In my software library, there exists a map function with the following definitions: function map<T, U>(f: (x: T) => U, a: Array<T>): Array<U> function map<T, U>(f: (x: T) => U, a: Functor<T>): Functor<U> Furtherm ...

"Troubleshooting a case where mongoDB's updateOne function is

I am in the process of removing certain references to objects within different sections (section1, section2, section3, others) in each file. Sample Document: { "_id": "64a3268474aa29e72b40c521", "name": "Test", ...

Retrieving Information from an Angular 2 Component

Struggling to figure this out, I am attempting to dynamically add user video data that includes a video URL. My goal is to access the data from the component so I can use it in my HTML. I've attempted the following approach. app.component.ts import ...

"Unlocking the Power of Angular: Mastering the Art of Ch

Within my angular 7 project, I am looking to chain together multiple HTTP Get requests. However, I want each call to wait until the previous one has completed even if I don't require the response directly in the next call. I am trying to avoid nestin ...

Nest may struggle with resolving dependencies at times, but rest assured they are indeed present

I've encountered a strange issue. Nest is flagging a missing dependency in a service, but only when that service is Injected by multiple other services. cleaning.module.ts @Module({ imports: [ //Just a few repos ], providers: [ ServicesService, ...

Implementation of setProperties method on LineLayer in MapBox encounters resolution issues

I am currently utilizing the Android Mapbox SDK to integrate a VectorSource into a MapboxMap and then I am trying to incorporate a LineLayer onto the map as well. My version is 5.1.3 This code will be written in TypeScript due to its compatibility with t ...

Mapped Generics in Typescript allows you to manipulate and

Currently, I am attempting to utilize TypeScript generics in order to transform them into a new object structure. Essentially, my goal is to change: { key: { handler: () => string }, key2: { hander: () => number }, } to: ...

Troubleshooting Primevue Data table styling issues in Vue3

Currently, I am attempting to incorporate grids into my data table using primevue library. However, despite following the provided example at https://www.primefaces.org/primevue/datatable/dynamiccolumns, the gridlines are not appearing on the table. The c ...

Reviewing for the presence of "Undefined" in the conditional statement within Transpiled Javascript code for

While perusing through some transpiled Angular code, I came across this snippet: var __decorate = (undefined && undefined.__decorate) || function (decorators, target, key, desc) { I'm puzzled by the usage of undefined in this context. Can an ...

Avoiding misreading email content with mail-listener2 - Tips for ensuring your function reads the correct emails

My E2E test utilizes the mail-listener2 to fetch emails. Though it generally works well, there is one recurring issue that I am struggling to resolve. Despite my extensive search for solutions online, the fix still eludes me. The problem arises when I use ...

When trying to click a button in an ion-footer, the (click) function may not execute initially

I have been working on creating a chat feature with Ionic 2, utilizing the keyboard-attach directive. //View <ion-footer [keyboardAttach]="content"> <ion-toolbar class="text_send"> <ion-textarea class="textarea" fz-elastic ...

Angular 8 is throwing an error stating that the property 'token' is not recognized on the 'Object' data type

As a newcomer to Angular, I have been following the MEAN Stack - Mean Auth App Tutorial in Angular 2. However, since I am using Angular 8, some of the code is deprecated due to recent updates. I have encountered an issue with the code bel ...

Is there a method in TypeScript to make an enum more dynamic by parameterizing it?

I've defined this enum in our codebase. enum EventDesc { EVENT1 = 'event 1', EVENT2 = 'event 2', EVENT3 = 'event 3' } The backend has EVENT1, EVENT2, EVENT3 as event types. On the UI, we display event 1, event 2, a ...