skip to Main Content

I need to take the inner html of my custom component as an input or assign it as a variable.

for EX:

<my-component>Hello There</my-component>

how do I assign the "Hello There" as a variable inside my component?

i tried document.getElementById(id).innerHTML but it’s not that great

2

Answers


  1. Recommend working through the tour of heroes tutorial.

    document.getElementById isn’t something we do often (or ever really) in an angular application.

    You can use <ng-content></ng-content> inside your my-component component template to project the content leaving the parent as you have in your question.

    Or you can use an @Input() message: string input binding inside the component and pass the message to the child via

    <my-component message="Hello There"></my-component>
    
    // or <my-component message="Hello There" /> if you're on latest angular
    
    Login or Signup to reply.
  2. I am sure there are better practices but you can use this aproach.

    In your component, add a @ContentChild decorator to the variable where you want to assign the projected content.

    ...
    
      @ContentChild('content') content;
    
      ngAfterContentInit() { // this hook because content has to load first
        this.content.nativeElement.textContent  // <- you can access the content with this attribute
      }
    ...
    
    <my-component>
      <span #content>Hello There</span>
    </my-component>
    

    In the example above, the @ContentChild decorator is assigned to content and uses the same name as the template reference variable #content.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search