【问题标题】:Angular - Only allow text in ng-contentAngular - 只允许 ng-content 中的文本
【发布时间】:2017-08-31 13:40:27
【问题描述】:

是否可以将我的 ng-content 标签之间的内容限制为纯文本?我该怎么做?

我知道我可以使用类型安全的输入参数作为替代方案,但我仍然想知道这是否可行。谢谢!

【问题讨论】:

  • 为什么要这样做而不是只使用输入属性?
  • 主要是个人喜好,我觉得它更容易使用/阅读。如有必要,我会使用输入,但我很好奇...

标签: angular transclusion


【解决方案1】:
@Component({
  selector: 'foo',
  template: `
    <div #wrapper>
     <ng-content></ng-content>
    </div>
  `
})
export class FooComponent {
  @ViewChild('wrapper') wrapper;

  ngAfterContentInit() {
    var nodes = this.wrapper.childNodes;
    for (var i = 0; i < nodes.length; i++) {
      if (nodes[i].nodeType != Node.TEXT_NODE) // or if (nodes[i].nodeType != 3)
      throw 'Only text is supported as content
    }
  }
}

另见javascript check if child node is element or text node

【讨论】:

  • 感谢您的解决方案。我希望它得到直接支持,但看到这种方法会很有帮助。
  • 我确定目前没有。很高兴听到这对你有用。
【解决方案2】:

您可以创建一个指令来获取内部文本并替换元素内容。

例子

@Directive({
  selector: '[text-content]'
})
export class TextContentDirective implements OnInit {

  constructor(
      private el: ElementRef
  ) {
  }

  ngOnInit(): void {
    this.extractTextContent()
  }

  private extractTextContent() {
    this.el.nativeElement.innerHTML = this.el.nativeElement.innerText
  }

}

您只想保留内部文本的位置:

<h1 text-content><ng-content select="dialog-header-title"></ng-content></h1>

输出:

<h1 text-content>My Title</h1>

【讨论】:

    猜你喜欢
    • 2015-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    • 1970-01-01
    • 2019-12-17
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多