Douwe de Vries
Douwe de Vries

Reputation: 101

is it possible to get the content (ng-content) of component as string?

We are building a design system and for our documentation we would like to display the code next to rendered components.

<br-code-example>
  <br-button type="primary">
    Primary default
  </br-button>
</br-code-example>

is possible to get what is in ng-content as a string (as well as keep it in ng-content so it gets rendered)?

<br-button type="primary">
  Primary default
</br-button>

Upvotes: 1

Views: 4534

Answers (2)

Douwe de Vries
Douwe de Vries

Reputation: 101

So we managed to get the results we needed by having the component.html of our pages being generated by a node script.

  • The br-code-example component has an input, code that takes in a string with the code.
  • Pages are written in markdown (with pieces of <br-code-example> html as described in the question.
  • A node script runs every time a markdown file is changes that:
    • Goes through each markdown file and searches for <br-code-example> tags
    • Takes what is between those tags and adds it as a code prop to the br-code-example
    • Converts the markdown to html
    • Saves the html as [page].component.html

Upvotes: 1

SiddAjmera
SiddAjmera

Reputation: 39432

Give a template variable to the ng-content tag. And then access it in the Component using ContentChild.

Try this:

import { Component, Input, ContentChild } from '@angular/core';

@Component({
  selector: 'hello',
  template: `
    <h1>Hello {{name}}!</h1>
    <ng-content #projected></ng-content>
  `,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
  @ContentChild('projected', { static: false }) projectedContent;

  ngAfterContentInit() {
    console.log('child: ', this.projectedContent.nativeElement.innerHTML);
  }
}

Here's a Working Code Example on StackBlitz for your ref.

Upvotes: 3

Related Questions