What I am trying to achieve is a dynamically generated html with some static links in it.
So, in a component, I have an array of objects:
let list = [{
type: 'container',
title: 'SIMPLE LIST'
description: '<ul>
<li>
<a href='/some/link#A'>A</a> // or [href] or routerLink+fragment
</li>
<li>
<a href='/some/link#B'>B</a>
</li>
<li>
<a href='/some/link#C'>C</a>
</li>
</ul>'
}, {
type: 'container',
title: 'SIMPLE ICON'
description: '<mat-icon class="material-icons">launch</mat-icon>'
}]
Then I pass it to a service which sanitize the description
key via bypassSecurityTrustHtml()
(from DomSanitzer
):
export class myDynamicBuilder {
content: Array<object>;
constructor(content, sanitizer) {
content.forEach(each => {
if (item.hasOwnProperty('description') && typeof item['description'] === 'string') {
item['description'] = sanitizer.bypassSecurityTrustHtml(item['description'])
}
this.content = content
})
}
}
Then in template:
<table *ngIf="(items?.content | filterContentBy: 'container').length">
<ng-template ngFor let-item [ngForOf]="(items?.content | filterContentBy:'container')">
<tr>
<td>
<b>{{item?.title}}</b>
</td>
</tr>
<tr>
<td colspan="2" class="second-row">
<p *ngIf="item.description" [innerHTML]="item.description"</p>
</td>
</tr>
</ng-template>
</table>
Links in description
field do not work as expected.:
if
href
is used as attribute a complete reload of the app is triggered (which is very bad)if the
routerLink
directive is used the link doesn't workif
[href]
is used I get the usual XSS security warning. So, I went back to the docs and I've found the convenientbypassSecurityTrustUrl
function. I modified the above mentioned service to replace strings after[href]
with the output of thebypassSecurityTrustUrl
and then throw the result in thebypassSecurityTrustHtml
function. Got a very nicely rendered HTML but with a non functional link.
How should I handle this scenario? I am thinking of building some pipes as shown in this question but not sure if this is the right way to do it. Another idea could be to let my service handle a new key (maybe links
) of the input object, sanitize via bypassSecurityTrustUrl
and then inject safe links in the sanitized HTML. Is there any defined way to do this? Thanks.