ViewContainerRef
提供方法 createEmbeddedView
(接受 TemplateRef
,用于渲染模板)和 createComponent
(接受 ComponentFactory
,用于渲染组件)。但是一个简单的 怎么样?字符串 ?
我看到的唯一解决方法是使用 DummyComponent
然后喂一个 document.createTextNode('string')
至 projectableNodes
.
@Component({ template: `<ng-content></ng-content>` }) class DummyComponent {}
const dummyComponentFactory = this.cfr.resoveComponentFactory(DummyComponent)
const nodes = [[document.createTextNode('string')]]
this.viewContainerRef.createComponent(dummyComponentFactory, 0, injector, nodes)
但这只是滥用 API,并且渲染一个简单的字符串会产生巨大的开销。
最佳答案
如果你真的想通过指令实现它,它是可能的。请引用下面的指令代码:-
import {
Directive,
Input,
NgIterable,
OnChanges,
OnInit,
Renderer2,
TemplateRef,
ViewContainerRef
} from "@angular/core";
@Directive({
selector: "[ngJoin]"
})
export class NgJoinDirective<T, U extends NgIterable<T> = NgIterable<T>>
implements OnInit, OnChanges {
@Input() ngJoinOf: any[];
@Input() ngJoinSeparator: string = ",";
constructor(
private _viewContainer: ViewContainerRef,
private _template: TemplateRef<any>,
private renderer2: Renderer2
) {}
ngOnChanges() {
this.createText();
}
ngOnInit() {
this.createText();
}
createText() {
if (this.ngJoinOf) {
this._viewContainer.clear();
console.log(this.ngJoinOf);
const container = this._template.createEmbeddedView({});
const parentNode = container.rootNodes[0];
const textNode = this.renderer2.createText(
this.ngJoinOf.join(this.ngJoinSeparator)
);
this.renderer2.insertBefore(parentNode, textNode, parentNode.firstChild);
this._viewContainer.insert(container);
}
}
}
并在 html 中使用,如下所示:-<p *ngJoin="let item of arr;separator: '/'">
如果您不提供分隔符,它将采用 , 作为默认分隔符。工作堆栈 Blitz :-
https://stackblitz.com/edit/angular-rumkzc?file=src/app/app.component.html
如果您只是想通过使用分隔符加入模板来打印数组,管道将是一个理想的选择,而不是指令。这样的管道由库提供。
https://github.com/fknop/angular-pipes
管道名称是 join。
注意:- 我没有处理过,任何边缘情况,你可能想要处理。
关于angular - 如何从结构指令呈现字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64809651/