【问题标题】:Replace HTML tag with text Angular 6用文本Angular 6替换HTML标签
【发布时间】:2018-06-30 08:02:41
【问题描述】:

我想使用 HTML 标记更改代码中的特定单词,并使用 themecolor 类更改我的文本样式。

<h2 class="mb-30" [innerHTML]="main_title"></h2>

结果预览:

这是文字。

我想将&lt;span class="themecolor"&gt;text&lt;/span&gt; 替换为text

我使用 Angular 6 构建了我的应用程序

【问题讨论】:

    标签: javascript angular angular-material angular6


    【解决方案1】:

    不知道为什么需要这样的功能,因为 Angular 是基于组件的,你通过选择器注入了 html。

    无论如何, stackblitz

    bindind 在这一行中如您所愿发生:

    <h2 class="mb-30" [innerHTML]="main_title"></h2>
    

    我所做的只是用您在 app.component.ts

    中选择的自定义 HTML 实例化 ma​​in_title

    另外,请注意,我使用 ngDoCheck 来检测文本输入的变化。

    这将允许您在文本框内输入 HTML(实际上首选 textarea)。

    【讨论】:

    • 我想用 css 改变我的文本的样式。这不是我的答案@monogate
    【解决方案2】:

    @angular/core中使用渲染器2

    ts 文件

    import { Component, OnInit, Input, ViewChild, ElementRef, Renderer2 } from '@angular/core';
    
    @Component({
      selector: 'app-custom-html',
      templateUrl: './app-custom-html.component.html',
      styleUrls: ['./app-custom-html.component.scss']
    })
    export class CustomHtmlComponent implements OnInit
    {
    
      @Input() public text: string;
      @ViewChild('container') public container: ElementRef;
      constructor(private renderer: Renderer2) { }
    
      ngOnInit()
      {
        const span = this.renderer.createElement('span');
        this.renderer.addClass(span, 'my-class');
        const text = this.renderer.createText(v.text);
        this.renderer.appendChild(span, text);
    
        this.renderer.appendChild(this.container.nativeElement, div);
      }
    }
    

    HTML 文件

    <div #container></div>
    

    【讨论】:

      【解决方案3】:
      property: string = "Text";
      
      Use [innerText]="property"
      <p [innerText]="property/variable"></p>
      

      这会将文本插入到您的 html 中

      【讨论】:

        猜你喜欢
        • 2019-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-01
        • 1970-01-01
        • 2011-03-13
        • 2014-08-13
        • 1970-01-01
        相关资源
        最近更新 更多