【发布时间】:2019-03-29 13:00:02
【问题描述】:
我有一个简单的组件
@Component({
selector: '[my-component]',
template: `<i>1</i><p>content</p><b>2</b>`
})
export class MyComponent {
public tagName: string;
}
另一个实例化第一个:
export class AppComponent implements OnInit {
@ViewChild("myContainer", { read: ViewContainerRef }) container;
constructor(
private viewContainer: ViewContainerRef,
private resolver: ComponentFactoryResolver) {
}
ngOnInit() {
this.container.clear();
const compFactory = this.resolver.resolveComponentFactory(MyComponent);
const componentRef = this.container.createComponent(compFactory);
componentRef.instance.tagName = 'span';
}
}
AppComponent的模板只是
<template #myContainer></template>
,所以输出是
<div my-component><i>1</i><p>content</p><b>2</b></div>
我要做的是在实例化过程中自定义MyComponent 模板,并将其p 标记替换为名称应为tagName 的标记。在执行AppComponent.ngOnInit 方法时,我知道MyComponent 创建之前的标签名称。
我要解决的另一项任务是MyComponent 包装标签名称定制。将<div my-component>... 替换为<span my-component>...,其中“span”是所需的标签名称,也称为AppComponent.ngOnInit。
那么是否有可能以编程方式提供这样的自定义并获得以下信息:
<span my-component><i>1</i><span>content</span><b>2</b></span>
? tagName 可以是任何允许的 HTML 标记,并且 ngIf/Switch 不是一个选项。我为快速潜水创建了演示:https://stackblitz.com/edit/angular-zngyoa
【问题讨论】:
标签: html angular angular-components angular-dynamic-components