gpt4 book ai didi

angular - 组件 Angular 6 中的动态模板

转载 作者:太空狗 更新时间:2023-10-29 18:22:35 24 4
gpt4 key购买 nike

我是 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 中是非常反模式的事实之外,我相信您可以通过将 CommonModule 添加到 NgModule 声明来修复您的错误:

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>

:

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 包将不再包含编译器,因此使您的应用程序更小更快。此外,这看起来好多了:)

关于angular - 组件 Angular 6 中的动态模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52664111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com