我重构字符串。因此,为什么我需要一个带有ComponentFactoryResolver
的组件:
@Component({
selector: '[text-in-message]',
template: `<ng-template chunk></ng-template>`,
})
export class TextInMessageComponent implements OnInit {
@Input() message: string;
@ViewChild(ChunkInMessageDirective, { static: true })
chunkOfMessage: ChunkInMessageDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
问题是,当我使用viewContainerRef.createComponent
时会创建div
块。而且,就我而言,我需要一些inline
元素,例如span
。我尝试了styles: [':host{display: "inlilne"}'],
,但是它不起作用。如何为创建的组件或绑定样式设置标签?
而且,在这个组件中,我有方法:
ngOnInit() {
this.refactorText();
}
refactorText() {
const { viewContainerRef } = this.chunkOfMessage;
viewContainerRef.clear();
const textNodeFactory = this.componentFactoryResolver.resolveComponentFactory(
TextNodeComponent
);
const textNodeComponentRef: any = viewContainerRef.createComponent(
textNodeFactory
);
(textNodeComponentRef.instance as TextNodeComponent).text = this.message;
}
[如果有人需要,也为TextNodeComponent
。它可以有一个随机模板。
@Component({
selector: '[text-chunk-in-message]',
template: `{{ text }}`,
})
export class TextNodeComponent implements OnInit {
@Input() text: string;
constructor() {}
ngOnInit() {}
}
结果我得到:
<div text-chunk-in-message="">A mere glimpse of Chuck Norris bearded member gave engineers the idea for the Alaska Pipeline.</div>
但是我需要span
而不是div
您必须更改TextNodeComponent
的选择器以包括范围:
@Component({
selector: 'span[text-chunk-in-message]',
template: `{{ text }}`,
})
这样,它不会默认为<div>
。
工作示例: