组件角度6中的动态模板

时间:2018-10-05 10:58:44

标签: angular ng-template

我是Angular的新手,所以对不起行话,我感到抱歉。 我正在尝试在组件中动态使用templateURL(html),Class函数将保持不变,但是html会根据binType

而变化

这是我的组件类来源

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

declare var module: {
  id: string;
}

@Component({
  selector: 'app-cart-bin',
  styleUrls: ['./cart-bin.component.css'],  
  template: ` 
      <ng-template #dynamicTemplate></ng-template>
    `

})

export class CartBinComponent implements AfterViewInit, OnInit {

  @ViewChild('dynamicTemplate', {read: ViewContainerRef}) dynamicTemplate;


  public cols = 3;
  public rows = 3;

  @Input() binType = "";

  @Input() toteList = [];

  @Output() callbackMethod = new EventEmitter<string>();

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

  ngOnInit() {
    console.log(this.binType);
  }

  ngAfterViewInit() {

    let tmpObj;

    console.log(tmpObj);

    if ((this.binType) == "2") {
      tmpObj = {
        moduleId: module.id,
        templateUrl : './cart-bin.component_02.html'
      };
    } else {
      tmpObj = {
        moduleId: module.id,
        templateUrl : './cart-bin.component_01.html'
      };
    }

    console.log(tmpObj);

    const tmpCmp = Component(tmpObj)(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);
    });
}

  getToteBoxClass(toteData){
    ...
  } 

  getToteIcon(toteData){
    ...
  }

  toteSaveClick(toteData){
    ...
  }
}

这正在编译,但模板未解析,并出现以下错误

ERROR Error: Template parse errors:
Can't bind to 'ngStyle' since it isn't a known property of 'div'.

HTML是正确的,我直接将其用作@Component TypeDecorator的一部分

1 个答案:

答案 0 :(得分:3)

除了使用编译器和创建动态组件在角度上是非常反模式的事实之外,我相信您可以通过在NgModule声明中添加CommonModule来解决错误:

NgModule({imports: [CommonModule], declarations: [tmpCmp]})

最好在模板中使用ngSwitchCase,创建两个从基本组件继承但具有不同模板的组件,并根据binType使其呈现一个或另一个组件:

模板:

<ng-container [ngSwitch]="binType">
  <cart-bin-1 *ngSwitchCase="1"></cart-bin-1>
  <cart-bin-2 *ngSwitchCase="2"></cart-bin-2>
</ng-container>

ts:

export abstract class CartBin {
  // some common cart bin logic here:
}


@Component({
  selector: 'cart-bin-1',
  templateUrl: './cart-bin.component_01.html' 
})
export class CartBin1 extends CartBin {

}

@Component({
  selector: 'cart-bin-2',
  templateUrl: './cart-bin.component_02.html' 
})
export class CartBin2 extends CartBin  {

}

使用此命令的好处是AOT捆绑包将不再包含编译器,从而使您的应用程序更小,更快。而且,这看起来好多了:)