角度。 ng-template中的自定义标签选择器

问题描述 投票:1回答:1

我重构字符串。因此,为什么我需要一个带有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

angular angular9
1个回答
1
投票

您必须更改TextNodeComponent的选择器以包括范围:

@Component({
  selector: 'span[text-chunk-in-message]',
  template: `{{ text }}`,
})

这样,它不会默认为<div>

工作示例:

stack

© www.soinside.com 2019 - 2024. All rights reserved.