【问题标题】:I want to include multiple html under same ts file?我想在同一个 ts 文件下包含多个 html?
【发布时间】:2019-04-04 14:11:30
【问题描述】:

我有一个组件,我想在其中包含多个 HTML 文件, 我正在使用 Angular 4,我想同时加载所有 HTML 文件。

我检查并发现使用 directive 可以做到这一点,但我无法看到一个示例。

有人可以推荐使用什么以及如何做到这一点吗?

我试过了,它不能正常工作:

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


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

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

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


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

【问题讨论】:

  • 请在 stackblitz 中分享至少最少的代码或工作演示,以便其他人可以了解到目前为止已经尝试过的内容以及需要更改的内容。您检查了吗? &lt;p [innerHTML]='bindWhatYouWantShow'&gt;&lt;/p&gt;
  • @worstCoder 我已经添加了我的代码

标签: html angular


【解决方案1】:

你可以尝试如下。

@Component({
    selector: 'register-page',
    template: `
            <div class="open-card-BG" *ngIf="registerView == 'regView1'">Reg View 1 Content</div>
            <div class="open-card-BG" *ngIf="registerView == 'regView2'">Reg View 2 Content</div>
            `,
    styleUrls: ['./register-page.component.scss'],
    providers: [RegisterService, Configuration, LocalStorageService]
})

export class Appcomponent {
    registerView = 'regView1';
}

参考这个SO thread 可能对你有帮助

【讨论】:

  • Reg View 1 Content
    在这个我必须写整个 html 代码,这个会很大
  • 这是thred中使用的选择器,那么我们可以为html页面创建选择器吗?
  • @DebashishDwivedi 是的,如果要加载的内容太多,第二种方法可能会有所帮助。其实分开比较好
猜你喜欢
  • 1970-01-01
  • 2022-10-15
  • 1970-01-01
  • 1970-01-01
  • 2012-02-17
  • 2019-11-27
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多