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.
1- install this library
npm i -D html-loader
============================================================
2- In webpack.config use html-loader for html files
============================================================
3- If you use ionic , you can copy webpack.config.js from the path "node_modules/@ionic/app-scripts/config/webpack.config.js" then add the html loader to it
=============================================================
4-If you use ionic In package.json add these lines
=============================================================
5-Then you can use it as below
======================================
6-If there is unresolved error with require function you can put it in declarations.d.ts file as the below :
declare var require: any;
It appears this way of creating dynamic templates will not be available to Angular 2 due to security matters. Unfortunate, coming from Angular 1 my previous application was dynamically driven this way.
For Angular 2 - This could be a differeny way of doing the same (link example below). By updating the template html files to be components in the application, then injecting them into (the place where you were trying to create the templateUrl with a string etc) view component template parameter as elements (using DynamicComponentLoader).
https://angular.io/docs/js/latest/api/core/DynamicComponentLoader-class.html
Compile your application with aot "ng serve --aot".
My solution:
Angular 2.0 ViewResolver Class
Not quite what you asked for, but it's worth mentioning:
Another simple solution, which works for most use cases, is to put the logic in the template itself, like so:
Downside for this solution is that your served js file ends up containing both templates, so this might be an issue for big templates (but only one template is actually rendered and the js size overhead is acceptable in many cases).
Update to @Eyal Vardi's answer (
ViewResolver
is deprecated):