I've been playing around with Angular 2 for the past few days and wondered if it was possible to provide a dynamic templateUrl
to the @View
decorator.
I have tried passing it a function and returning a string form it but the entire function just get's turned into a string.
I haven't really used Angular 1.x before either so I don't know if I'm just going about this in the wrong way, but is this possible, or is there a better way to create dynamic views?
For example I might want to display a form if the user is not logged in, but display a text message if they are logged in.
Something like this doesn't work:
@Component({
selector: 'my-component'
})
@View({
// This doesn't work
templateUrl: function() {
return this.isLoggedIn ? 'logged-in.html' : 'logged-out.html';
}
})
class MyComponent {
constructor() {
this.loggedIn = false;
}
}
Any help would be appreciated.
Although maybe not the most elegant solution, I used the DynamicComponentLoader and ElementRef to dynamically assign template value to a component. In fact, I was looking for a solution where I can add multiple custom components into a placeholder.
I tried service injection in the function as outlined by shmck this doesn't work as the services are not available yet when the template function is called. Indeed,
this
refers to the Window object.Reference URLs for the solution I used are to be found on: create dynamic anchorName/Components with ComponentResolver and ngFor in Angular2
I also refer this way to Plnkr1 and Plnkr2.
The site Dartdocs provides nice documentation on Angular 2 DynamicComponentLoader class, also applicable to TypeScript.
In short:
A simple Component as the to be used template
Constructor of the Component that holds all Components to be added (my app requires multiple childs to be included:
And the helper function to be put somewhere as util
Hope, github example for you will help you! There are example to compile dynamic html. So, you can load HTML by any of your Service and then compile it.
My solution:(The beauty about this is lazy loading for html and css files.)
This is home.componenet.ts
The directive I used and made few changes: This is in home.componenet.html
This is the directive for dynamic components: