带有字符串变量的 Angular 2 动态模板 url?

问题描述 投票:0回答:2
 @Component({
  selector: 'bancaComponent',
  templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}

还有其他方法吗? 谢谢:)

angular typescript angular2-template
2个回答
15
投票

试试这个解决方案:

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);
            });
    }
}

灵感来自:Angular 2/4 component with dynamic template or templateUrl

官方来源:https://angular.io/guide/dynamic-component-loader


0
投票

角 13

使用所需模板创建多个组件,然后像这样动态加载组件:

@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);
    }
}

来源

© www.soinside.com 2019 - 2024. All rights reserved.