6

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.

1 Answer 1

3

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;  
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hmm... this works ONLY if I have only one element. As soon as I have multiple elements the approach fails - what a pity stackblitz.com/edit/angular-6focgz Also the q arise does this work if the content is set by the DomSanitizer?
Yeah I see its working with your sample. Nevertheless I have two remarks: in the app.component you have @Component AND @Directive which I guess is a typo. I have updated my sample as well to meet my initial requirement. stackblitz.com/edit/angular-r1jsma. Unfortunately I have no clue how to initialize the Directive more properly. Any ideas?
try second way i added answer @LeO
In principal this works although I have some troubles with the CSS. One issue with my code is that I need to apply ::ng-deep which isn't my #1 preferred solution. Also I need to change little bit the content - which I thought I can do in one step. Anyway - I upvoted your response - and looking forward for a solution which allows some manipulation. Thx anyway.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.