Dynamic template in templatURL in angular2
Solution 1:
And as you can see in this issue on the Angular repo, most probably we won't get that directive. There has been a long discussion whether we need this directive or not, and if not provided how we can implement it by our self.
I tried to make a simple example of how it can be implemented.
@Component({
selector: 'my-ng-include',
template: '<div #myNgIncludeContent></div>'
})
export class MyNgInclude implements OnInit {
@Input('src')
private templateUrl: string;
@ViewChild('myNgIncludeContent', { read: ViewContainerRef })
protected contentTarget: ViewContainerRef;
constructor(private componentResolver: ComponentResolver) {}
ngOnInit() {
var dynamicComponent = this.createContentComponent(this.templateUrl);
this.componentResolver.resolveComponent(dynamicComponent)
.then((factory: any) => this.contentTarget.createComponent(factory));
}
createContentComponent(templateUrl) {
@Component({
selector: 'my-ng-include-content',
templateUrl: templateUrl,
directives: FORM_DIRECTIVES,
})
class MyNgIncludeContent {}
return MyNgIncludeContent ;
}
}
For a demo check this Plunker.
Solution 2:
Actually angular 2 has not featured this in the current build. Also as per the links added, I don't think this feature will be included.
A piece of javascript to dynamically add template using ajax call may be used.
Or possibly in future a dynamic template loader library will be available for use.
Solution 3:
As of alpha.46 (and with ES6 JS):
In the parent file import file you wanted to include:
@Component({
selector: 'account'
})
@View({
templateUrl: './folder/containing/template.html'
})
Easy as that.
If you meant to import a component, this is what you do in the parent file:
import ComponentClassName from './folder/with/componentName';
...
@View({
directives: [ComponentClassName]
})
And inside the imported file of the child/component:
Define your ComponentClassName
(you may add templateUrl
to the @View
just as demonstrated at the top).
Don't forget to export default ComponentClassName;
at the bottom of the file.
There are not many examples in the official Angular 2 docs, but you stumble across it every once in a while.