6

Well... in angular 1.x.y is

angular.module('myApp', []).directive('myDirective', function(){
    return {
       templateUrl : function(tElement, iAttrs){
           return 'http://' + iAttrs.myDirective // More...
       } 
    }
});

But.. In Angular2

@Component({
    selector: 'my-Directive',
    templateUrl: 'http://???' 
})
class HelloWorld {
}

Well, in the doc say only a String. As it is handled to be a function in angular2 ?

Ankit Singh
  • 24,525
  • 11
  • 66
  • 89
Alejo Next
  • 383
  • 1
  • 15
  • Use templateUrl: 'http://...' – Michael Kang Mar 18 '16 at 04:54
  • Its kind of similar question as [this question](http://stackoverflow.com/questions/36071097/how-can-i-have-dynamic-templateurl-for-angular2-component) with no answer... – Pankaj Parkar Mar 18 '16 at 07:58
  • @pixelbits OP wanted to have, dynamic `templateUrl` based on value passed from parent component.. the similar question I asked yesterday but didn't find any answer.. could you looked at my previous comment too. – Pankaj Parkar Mar 18 '16 at 08:10
  • Component templates are compiled at runtime in Angular 2 by the Angular Compiler. Therefore you can't choose your template dynamically with a function. EDIT: You could solve this problem by creating a component, which is using the [dynamic component loader](https://angular.io/guide/dynamic-component-loader) to dynamically create a component and then display it within your parent component. – Thomas Gassmann Sep 03 '17 at 11:09

1 Answers1

0

I had to implement something similar and my solution was the same as Thomas Gassmann's comment above, so I decided to share.

Currently (angular 4.4.5) @Component decorator only accepts a string, therefore the template is not dynamically compiled like on angularJS. However you can implement multiple components and switch the component dynamically. Example below:

https://stackblitz.com/edit/angular-dynamic-templateurl

silvio
  • 5,651
  • 2
  • 17
  • 14