简体   繁体   English

Angular - 只允许 ng-content 中的文本

[英]Angular - Only allow text in ng-content

Is it possible to limit the contents between my ng-content tags to just text?是否可以将我的 ng-content 标签之间的内容限制为文本? How can I do this?我怎样才能做到这一点?

I understand I can use a type-safe input parameter as an alternative, but I would still like to know if this is possible.我知道我可以使用类型安全的输入参数作为替代,但我仍然想知道这是否可行。 Thanks!谢谢!

@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
    }
  }
}

See also javascript check if child node is element or text node另见javascript检查子节点是元素还是文本节点

You can create a directive which get inner text and replace element content.您可以创建一个获取内部文本并替换元素内容的指令。

Example例子

@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
  }

}

where you want to keep only the internal text:您只想保留内部文本的位置:

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

output:输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM