angulartransclusion

Angular - Only allow text in ng-content


Is it possible to limit the contents between my ng-content tags to just text? 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!


Solution

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