0

I have an Angular component that accepts it's content via Content Projection (). Different components can project different HTML into it. For e.g. suppose the component shows a Toast message, like

<my-toast>Some HTML Here</my-toast>

Some components using it may project warnings (HTML). Others may project errors (again HTML). So far so good.

In my codebase there is a bunch of components using this, which project the exact same HTML content. For e.g.

Component 1: <my-toast> <div style="font-size":large><b>Warning message</b></div></my-toast>

Component 2: <my-toast> <div style="font-size":large><b>Warning message</b></div></my-toast>

Component 3: <my-toast> <div style="font-size":large><b>Warning message</b></div></my-toast>

Is there a way in Angular to encapsulate this HTML at a common place rather than repeating it verbatim in each component that uses ? I dont want to create a component for this, but open to something like TemplateRefs <div style="font-size":large><b>Warning message</b></div>

Viking22
  • 545
  • 1
  • 7
  • 19
  • You can create a warning-toast component for the whole example or just for the warning div and project a one-line component. You can theoretically hold this template in a service or something and inject it into the componet using a funtion but that is very bad and unmaintable approach – Yousaf Raza Sep 02 '22 at 05:16
  • Theoretically hold a template? This is what I am not sure how? TemplateRef or just a string. A string cannot be projected as HTML – Viking22 Sep 02 '22 at 18:13
  • 1
    I am referring to this trick https://stackoverflow.com/questions/65705407/create-templateref-in-a-angular-10-service but I do not encourage this in any way as it is just a hacky way to pass a template around – Yousaf Raza Sep 02 '22 at 19:47

1 Answers1

0

you have many options, one would be to define a class in the SCSS of your toast component

:host {
  &.warn {
    font-size: large;
    font-weight: bold;
  }
}

another solution is to accept a Type as input to your toast

<div *ngIf="toastType === 'warn'" style="font-size:large"><b>
 <ng-content></ng-content>
</b></div>
<ng-container *ngIf="toastType === undefined">
   <ng-content></ng-content>
</ng-container>
Zerotwelve
  • 2,087
  • 1
  • 9
  • 24
  • The toast is just an example. My question is more generic. How do I store a block of HTML in my app, so that it can be projected from various consumers (like Comp1, Comp2) into another component that uses Content Projection (like My-Toast) – Viking22 Sep 02 '22 at 18:12
  • 1
    Well if you want a pice of code to be reused multiple times, the you create a component ;) as simple as that – Zerotwelve Sep 03 '22 at 19:04