2

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!

2
  • Why do you want to do this vs just using an input property? Commented Apr 5, 2017 at 19:10
  • Personal preference mainly, I find it easier to use/read. I will use an input if necessary, but I am curious... Commented Apr 5, 2017 at 19:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution. I was hoping that it was directly supported, but it's helpful to see this approach.
I'm sure there currently isn't. Glad to hear this works for you.
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.