angular - Angular ivy 中的 renderComponent 带有额外的组件/指令声明
问题描述
这是在 ivy 中渲染动态惰性组件的示例:
import { ɵrenderComponent as renderComponent, Injector } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<app-lazy></app-lazy>
`
})
export class AppComponent {
constructor(injector: Injector) {
import('./lazy.component').then(({ LazyComponent }) => {
renderComponent(LazyComponent, {
injector,
host: 'app-lazy'
});
});
}
}
如果我们需要在中使用额外的组件/指令,我该怎么办lazy.component
?
解决方案
你需要一个定制的装饰器
import {
Component,
Type,
ɵComponentDef as ComponentDef,
ɵDirectiveDef as DirectiveDef,
ɵPipeDef as PipeDef
} from '@angular/core';
@Component(...)
@ComponentDeps({
directives: [...], //***extra component/directive you want***
pipes: [...] //***extra pipe, like: JsonPipe...***
})
export class LazyComponent{
...
}
export interface ComponentDepsConfig {
directives?: Type<any>[];
pipes?: Type<any>[];
}
function getDirectiveDef<T>(t: Type<T>): DirectiveDef<T> {
if (t['ɵdir']) {
return t['ɵdir'] as DirectiveDef<T>;
}
if (t['ɵcmp']) {
return t['ɵcmp'] as ComponentDef<T>;
}
throw new Error('No Angular definition found for ' + t.name);
}
function getDirectiveDefs(types: Type<any>[]): DirectiveDef<any>[] {
return types.map(t => getDirectiveDef(t));
}
function getPipeDef<T>(t: Type<T>): PipeDef<T> {
if (t['ɵpipe']) {
return t['ɵpipe'] as PipeDef<T>;
}
throw new Error('No Angular definition found for ' + t.name);
}
export function getPipeDefs(types: Type<any>[]): PipeDef<any>[] {
return types.map(t => getPipeDef(t));
}
export function ComponentDeps(config: ComponentDepsConfig) {
return (componentType: Type<any>) => {
const def = componentType['ɵcmp'] || componentType['ngComponentDef'];
// directives or components
def.directiveDefs = [
...getDirectiveDefs(config.directives || [])
];
// pipes
def.pipeDefs = [
...getPipeDefs(config.pipes || [])
];
};
}
推荐阅读
- python-3.x - 为什么在使用类继承时出现“无法腌制模块对象错误”?
- python - Numpy - 有效地将数组元素与另一个元素的规则间隔组合起来
- javascript - 如何将输入值写入 PHP 中的文件?
- arrays - 在 C 编程中打印数组的元素
- asp.net-core - 防止包含跨域脚本-asp.net core 5.0 中的自我 XSS
- string - 使用选择字符串从 1000 多个文件中输出列表
- python - 获取 dir() 的简洁版本
- javascript - 如何更改嵌套标记行中外部标记的 innerText?
- vba - 删除所有使用已知密码锁定的 Word 宏
- reactjs - 在单个 spa microfrond end root-config 中添加反应组件