Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular HTML string - rename attributes

I have a HTML string like

 <span class="diff-html-changed" id="1" changes="MyText" >test </span>

and I want to display the text as html. I include it like

displayedContentInTemplate: SafeHtml;
private sanitized: DomSanitizer,
....
displayedContentInTemplate = this.sanitized.bypassSecurityTrustHtml(contentAsString);

My problem is that the content of changes is not displayed. Therefore I thought to rename changes into title. This would display MyText when hovering the text.

How to change the attribute changes properly? A simple replace within the string might replace text which will belongs to the displayed text. And with simple creation of a HTML document I have no clue how to change the attributes name.

like image 306
LeO Avatar asked Jun 10 '20 09:06

LeO


1 Answers

Demo You can do it with hostlistener and directive create one directive

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

@Directive({
  selector: '[changes]'
})
export class HoverClassDirective {

  constructor(public elementRef:ElementRef) { }
  @Input('changes') changes:any;  

  @HostListener('mouseenter') onMouseEnter() {
    console.log()
    this.elementRef.nativeElement.title=this.changes;
 }

  @HostListener('mouseleave') onMouseLeave() {
    this.elementRef.nativeElement.title=this.changes;
  }

}

Demo second way is css you can put below code to sytle.css to also effect dynamically added

span {
  position: relative; 
}
span::after{
  position: absolute;
  display: none;  
}
span::after {
  content: attr(changes);  
  top: -20;
  left: -5px;
  background: white;
  border-radius: 4px;  
  padding: 2px 6px;
  white-space: nowrap;
  color: black;
  border: 1px solid gray
}
span:hover::after {
  display: block;  
}
like image 115
mr. pc_coder Avatar answered Nov 15 '22 01:11

mr. pc_coder