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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With