'How can I make dynamic url to external site in angular5?
When I'm trying to make link like this:
<a [href]="getUrl()">click me</a>
getUrl() {
return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com');
}
It's not clickable. When I hover over link, I can see that url is there but click event isn't, I think.
There is no difference if I'm using sanitizer method or not.
Edit:
I will give you some additional background what i want to do. I just need to append dynamically some html. At first place a started with:
<div [innerHTML]="getHtml()"
getHtml() {
return this.domSanitizer.bypassSecurityTrustHtml(html);
}
but doing this in that way links are broken. you can open it only with ppm. When i'm not using bypassSecurityTrustHtml method then links are working, but most of styling doesn't...
For now, I also tried:
for (const el of this.div.nativeElement.getElementsByTagName('a')) {
// that way
this.renderer.listen(el, 'click', () => {this.getUrl()});
// or that way
el.onclick = function (event) {
window.open('http://testurl.com');
};
}
but it's not working as well.
What is working:
// i'm not angular expert, i don't know why, but links are working with this
changeDetection: ChangeDetectionStrategy.OnPush
also in this way we can accomplish to solve my problem, but i don't like it:
@HostListener('mouseup', ['$event'])
onClick(event) {
if(event.target && event.target.href) {
window.open(event.target.href);
}
}
Solution 1:[1]
My final workaround:
@HostListener('mouseup', ['$event'])
onClick(event) {
if (event.target && (event.target.href || event.target.closest('a')) && event.target.closest('.notificationHtmlDiv')) {
const a = event.target.href ? event.target : event.target.closest('a');
let target = a.target ? a.target : '_self';
if(event.button === 1) {
target = '_blank';
}
window.open(a.href, target);
}
}
It seems that angular is blocking click events on SafeHtml, because when I tried to add onclick on div (outside dynamically added html block) it worked fine, but when I did the same for <a>
tag (inside dynamically added html) then it doesn't worked at all.
Solution 2:[2]
You can do below changes --
- HTML-
<a href="#" (click)="getUrl()">Click me</a>
- TypeScript File - -- Import DomSanitizer from platform-browser
import { DomSanitizer, SafeResourceUrl, SafeUrl} from '@angular/platform-browser';
Make a instance of Domsanitizer
constructor(private domSanitizer: DomSanitizer) {}
Call your method
getUrl() {
return this.domSanitizer.bypassSecurityTrustUrl('http://sampleUrl.com');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 |