加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:47:14 所属栏目:安全 来源:网络整理
导读:@Component({ selector: 'bancaComponent',templateUrl: '{{str}}'})export class BancaComponent implements OnInit { str: String; constructor(private http: Http) { } ngOnInit(): void { this.str = "./file.component.html";} 还有另一种方法吗? 谢
@Component({
  selector: 'bancaComponent',templateUrl: '{{str}}'
})
export class BancaComponent implements OnInit {
  str: String;
  constructor(private http: Http) { }
  ngOnInit(): void {
  this.str = "./file.component.html";
}

还有另一种方法吗?
谢谢 :)

解决方法

尝试此解决方案:

import {
  Compiler,Component,Injector,VERSION,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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读