angular - 如何从结构指令呈现字符串?

标签 angular

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/

相关文章:

node.js - 使用 angular2+ 服务、mongoDB 和 NodeJs 编辑对象

html - 如何为背景网址提供图像路径

angular - 如何将 angular cli 从 1.0.1 降级到 1.0.0

css - 以 Angular 7 覆盖 body 背景颜色

Angular2 - react 形式和多个复选框行为不正确

javascript - 无法将 Object[] 分配给 Observable<Object[]>

javascript - Angular 2 : ngFor loop undefined value

javascript - 在 Angular 5 中将带有 geojson 层的 Leaflet map 导出为 png

javascript - 根据对象数组中的属性过滤掉非空和未定义的项目

angular - `@HostListener` 的 `e: TouchEvent` 导致 Firefox 崩溃 "ReferenceError: TouchEvent is not defined."