Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Angular4 routerLink inside innerHTML turned to lowercase

I have a cmd where I get the content of the page from the server. Then content can include HTML and links. The problem is when I display this data the links don't work. When looking at page source it turns out that "routerLink" is transformed into "router link" and that's why it probably doesn't work. Here is my code:

My class, notice that routerLink is in camelcase here:

export class TwoComponent implements OnInit {
  data = '<a routerLink="/one">ONE</a>'; //this will actually come from backend server

  constructor() { }

  ngOnInit() {}
}

And my html:

<div [innerHTML]="data | bypassSecurity"></div>

And when i load this page and look at the source the routerLink is now in lowercase:

<a routerlink="/one">ONE</a>

At first, i thought it's the bypassSecurity pipe that responsible but I checked the output of the pipe and routerLink was still in camel case there. So it seems like it happens somewhere else. Just in case here is my bypassSecurity pipe too:

export class BypassSecurityPipe implements PipeTransform {
  constructor(private sanitized: DomSanitizer) {}

  transform(value): any {
    return this.sanitized.bypassSecurityTrustHtml(value);
  }
}

Any advice on where and why this lowercase transformation happens would be appreciated :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

jcdsr's solution helped me a lot. I got this working by using it with DomSanitizer.

Here is how i did:

RouteTransformerDirective

import { Directive, ElementRef, HostListener } from '@angular/core';
import { Router } from '@angular/router';

@Directive({
  selector: '[routeTransformer]'
})
export class RouteTransformerDirective {

  constructor(private el: ElementRef, private router: Router) { }

  @HostListener('click', ['$event'])
  public onClick(event) {
    if (event.target.tagName === 'A') {
      this.router.navigate([event.target.getAttribute('href')]);
      event.preventDefault();
    } else {
      return;
    }
  }

};

Component

import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

public html: SafeHtml;

constructor(private sanitizer: DomSanitizer) {
    this.html = sanitizer.bypassSecurityTrustHtml('<a href="/something">Link</a>');
}

Template

<div [innerHtml]="html" routeTransformer></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...