16
 @Component({
  selector: 'bancaComponent',
  templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}

Is there another way to make it ? Thanks :)

2 Answers 2

17

Try this solution :

import
{
    Compiler, Component, Injector, ViewChild, NgModule, NgModuleRef,
    ViewContainerRef, AfterViewInit, OnInit
} from '@angular/core';

@Component({
    selector: 'bancaComponent',
    template: `<ng-container #dynamicTemplate></ng-container>`
    // or with a templateUrl
})
export class BancaComponent implements AfterViewInit, OnInit
{
    @ViewChild('dynamicTemplate', { read: ViewContainerRef }) dynamicTemplate;

    constructor(
        private _compiler: Compiler,
        private _injector: Injector,
        private _m: NgModuleRef<any>)
    {
    }

    ngAfterViewInit()
    {
        let myTemplateUrl = './file.component.html';

        if (MYCONDITION === MAEXPECTATION)
        {
            myTemplateUrl = './another-template.component.html';
        }

        const tmpCmp = Component({
            moduleId: module.id, templateUrl: myTemplateUrl
        })(class { });
        
        const tmpModule = NgModule({ declarations: [tmpCmp] })(class { });

        this._compiler.compileModuleAndAllComponentsAsync(tmpModule)
            .then((factories) =>
            {
                const f = factories.componentFactories[0];
                const cmpRef = f.create(this._injector, [], null, this._m);
                cmpRef.instance.name = 'dynamic';
                this.dynamicTemplate.insert(cmpRef.hostView);
            });
    }
}

Inspired from : Angular 2/4 component with dynamic template or templateUrl

Official source : https://angular.io/guide/dynamic-component-loader

Sign up to request clarification or add additional context in comments.

15 Comments

What is the error ? Take a look at the angular official solution for this kind of problem : angular.io/guide/dynamic-component-loader
@Boulboulouboule I'm working on Angular 5 and it gives me following error --- ERROR in ./src/app/app.component.ts Module not found: Error: Can't resolve ' myTemplateUrl'
was anyone able to resolve the error in angular 5+ versions?
getting this error with angular 9: screencast.com/t/HgRuD3fKD
First I got Error: Angular JIT compilation failed: '@angular/compiler' not loaded!. I fixed it by import "@angular/compiler";. Then I got Error: Component '' is not resolved: templateUrl: ./another-template.component.html. Did you run and wait for resolveComponentResources()'?. I can't find how to import / use resolveComponentResources. Could you please advise?
|
0

Angular 13

Create multiple components with the desired templates, then load the components in dynamically like so:

@Component({
    selector: 'app',
    template: `<ng-template #dynamic></ng-template>`
})
export class AppComponent implements AfterContentInit
{
    @ViewChild('dynamic', { static: true, read: ViewContainerRef })
    public dynamicContainer: ViewContainerRef;

    ngAfterContentInit()
    {
        const myComponentInstance = this.dynamicContainer.createComponent(MyComponent);
    }
}

source

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.