Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a "String" value to "Type" in Angular 2

I want to create a side menu in ionic 2 application where the page navigation component is placed in a external json file fetched with the help of menuService.getMenu function.

MY JSON structure:

"menu":[
        {
          "title":"Grid",
          "component":"GridPage"
        }
      ]

My Ts:

    this.menuService.getMenu().then((menu) => {
    this.menu = menu;
    });

    openPage(menu) {
      console.log("menu", menu.component);
      nav.setRoot(menu.component);
    }

Console log prints the string GridPage. I tried to convert using Type as Type(menu.component). But my result in console is a function with anonymous name. Someone please help me on getting the json string converted to component "Type" for navigation to work.

like image 869
AishApp Avatar asked Feb 12 '16 07:02

AishApp


People also ask

How do I convert a string to a number in TypeScript?

In typescript, there are numerous ways to convert a string to a number. We can use the '+' unary operator , Number(), parseInt() or parseFloat() function to convert string to number.

How do I convert a string to a date format in TypeScript?

Use the Date() constructor to convert a string to a Date object in TypeScript, e.g. const date = new Date('2024-07-21') . The Date() constructor takes a valid date string as a parameter and returns a Date object. Copied! We used the Date() constructor to convert a string to a Date object.

How do I convert a string to an integer in HTML?

syntax. parseInt(value); This function takes a string and converts it into an integer. If there is no integer present in the string, NaN will be the output.


1 Answers

I guess there is a way to get the type of a class by string but I don't know (I don't use TS). A simple workaround would be to

create a map from string to type

classes = {
  'MyClass1': MyClass1,
  'MyClass2': MyClass2,
  'Grid': Grid
}

and then just look the types up

class['Grid']

The disadvantage is that you need to know all supported classes in advance.

like image 106
Günter Zöchbauer Avatar answered Sep 20 '22 21:09

Günter Zöchbauer