【发布时间】:2019-03-10 20:56:14
【问题描述】:
我是 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 的一部分
【问题讨论】:
标签: angular ng-template