Friday, 15 April 2022

How do you create web components with customizable templates using Angular Elements?

I would like to create a library of web components using Angular Elements that have default templates but allow developers to override the output.

For example, consider a search-results component. I might have a default template that looks like this:

<h1>Search results for: </h1>

But a developer might want to change the output to this (as an arbitrary example -- it needs to be flexible):

<h1>You searched for <strong></strong></h1>

My first thought was to simply use ng-content like this:

<search-results>
    <h1>You searched for <strong></strong></h1>
</search-results>

However, this does not work and will literally output .

I then discovered that I could add a TemplateRef input parameter on my component and pass in an ng-template element which would parse expressions. This works well within an Angular application, but I'm not sure how to do this outside of an Angular context using the compiled web components that Angular Elements generates.

Can anyone explain how to do this?



from How do you create web components with customizable templates using Angular Elements?

No comments:

Post a Comment