简体   繁体   中英

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);
     }
  }

You can do below changes --

  1. HTML-

<a href="#" (click)="getUrl()">Click me</a>

  1. 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');
    }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM