How can I use dynamic templateUrl for Angular2 Component?

I wanted to load the templateUrl component based on the value passed from the parent component. I know that tt can go through property binding to a component using @Input , I gave an example below in which myHtml will be passed as templateName .

. But there is no way to access the @Input value inside the templateUrl function. I think templateUrl is the first thing you can evaluate by requesting HTML, after which all other code components will be executed.

As in angular 1, it is possible to pass some value from an attribute, and then I can use this value inside the templateUrl function as a parameter, as shown below.

 templateUrl: function(element, attrs){ //was getting value return '/app/templates/'+ attrs.myTemplateName + '.html' } 

But I can’t do the same thing in Angular2, because templateUrl strongly typed as string , so it does not accept the function as an attribute.

Is there a way to achieve this OR , have I missed something simple?

Edit

I have already considered this answer , which I do not want. In the response, the DOM uses a DynamicComponentLoader , which loads another component.

This is not what I wanted, because creating a new separate component to use different templateUrl does not make sense in my case.

Any idea how to implement this?

+4
source share
1 answer

Fighting something like that, but unfortunately you can't do it. Component templates are compiled at runtime. So basically, I would make a component that compiles other child components (which I actually did)

DynamicComponentLoader is deprecated. You should use the ComponentResolver class to load other components inside the main file, for example:

 function makeComponent( selector, template, ...more ) { @Component({ selector: selector, template: template }) class FakeComponent {} return FakeComponent; } @Component({ ... }) export class MainCmp implements OnInit { // place to insert @ViewChild('viewChild', {read: ViewContainerRef}) viewChild: ViewContainerRef; constructor(private compiler: ComponentResolver){} // or OnChanges, or event binding.. should work ngOnInit() { // decide on your custom logic here, get you @Input, whatever... // and you can actually make some custom dynamic component... let childCmp = makeComponent( custom, stuff, here ); // compile then insert in your location, defined by viewChild this.compiler.resolveComponent( childCmp ) .then( (compFactory:ComponentFactory) => this.viewChild.createComponent(compFactory) ) } } 
+3
source

All Articles