【问题标题】:Angular HTML string - rename attributesAngular HTML字符串 - 重命名属性
【发布时间】:2020-09-29 15:49:46
【问题描述】:

我有一个类似的 HTML 字符串

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

我想将文本显示为 html。我把它包括在内

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

我的问题是changes的内容没有显示出来。因此我想将changes 重命名为title。这将在悬停文本时显示MyText

如何正确更改属性changes?字符串中的简单替换可能会替换属于显示文本的文本。通过简单地创建 HTML 文档,我不知道如何更改属性名称。

【问题讨论】:

    标签: html angular sanitization


    【解决方案1】:

    Demo你可以用hostlistener和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 第二种方式是 css 你可以把下面的代码放到 sytle.css 也可以动态添加

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

    【讨论】:

    • 嗯...这仅在我只有一个元素时才有效。一旦我有多个元素,该方法就会失败 - 可惜stackblitz.com/edit/angular-6focgz 如果内容是由 DomSanitizer 设置的,那么 q 会出现吗?
    • 是的,我看到它与您的样本一起工作。尽管如此,我有两点意见:在app.component 中有@Component@Directive,我猜这是一个错字。我也更新了我的样本以满足我的初始要求。 stackblitz.com/edit/angular-r1jsma。不幸的是,我不知道如何更正确地初始化指令。有什么想法吗?
    • 尝试第二种方式我添加了答案@LeO
    • 虽然我在使用 CSS 时遇到了一些问题,但原则上这还是可行的。我的代码的一个问题是我需要应用::ng-deep,这不是我的#1 首选解决方案。我还需要稍微改变一下内容——我认为我可以一步完成。无论如何 - 我赞成你的回应 - 并期待一个允许一些操作的解决方案。无论如何谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-05-26
    • 2020-12-16
    • 2014-05-14
    • 2017-07-02
    • 2020-05-05
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多