0

In Angular 18 application, I am trying to load some mermaid content inside a under the ShadowRoot.

The parent component has encapsulation: ViewEncapsulation.ShadowDom,

I am using the below versions

"marked": "^12.0.2",
"marked-code-preview": "^1.3.7",
"mermaid": "^11.4.1",

HTML

<markdown lineNumbers [data]="responseText" mermaid></markdown>

TS

responseText = "Sample Flow Diagram:\nmermaid\ngraph LR\n A[Stage 1] --> B[Stage 2]\n B --> C[Stage 3]\n B --> D[Stage 4]\n D --> E[Stage 5]\n D --> F[Stage 6]\n D --> G[Stage 7]\n D --> H[Stage 8]\n\n\nThe diagram shows how the process flow:\n\n1. Stage 1 of the process.\n 2. Stage 2 of the process.\n3. Stage 3 of the process.\n4. Stage 4 of the process."

Here text is rendered as expected but mermaid content is showing as blank.

enter image description here

Looks mermaid couldn't find the element to render the content at runtime

enter image description here

Tried to below option also

 public ngAfterViewInit(): void {
    mermaid.initialize({ startOnLoad: false });
 }

Still not working

1 Answer 1

-1

The issue arises because ViewEncapsulation.ShadowDom encapsulates styles and DOM structure

I also faced an issue where the mermaid styles were not being applied within the Shadow DOM. If you run into this, ensure the styles are included globally or manually apply them inside the Shadow DOM. Try to use this solution.It will help you.

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom, // Add this here
})
export class AppComponent implements AfterViewInit {
  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit(): void {
    const shadowRoot = this.elementRef.nativeElement.shadowRoot;
    const mermaidElement = shadowRoot.querySelector('mermaid');

    if (mermaidElement) {
      mermaid.initialize({ startOnLoad: false });
      const graphDefinition = `
        graph LR
        A[Stage 1] --> B[Stage 2]
        B --> C[Stage 3]
        C --> D[Stage 4]
      `;
      mermaidElement.innerHTML = graphDefinition;
      mermaid.init(undefined, mermaidElement);
    } else {
      console.error('Mermaid element not found in Shadow DOM.');
    }
  }
}
Sign up to request clarification or add additional context in comments.

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.