【问题标题】:HTML Button tags are ignoredHTML 按钮标签被忽略
【发布时间】:2022-01-14 17:50:27
【问题描述】:

我的 Angular 项目有问题。我有一个带有标签的原始文本,例如:Listening to the rain, falling on the streets #Rain #Chill

现在我希望这 2 个标签是按钮,所以我在我的打字稿中有这个:

ngOnInit(): void {
    this.description = this.description.replace(/#(\w+)/g, '<button (click)="onHashtagClick($1)" class="hashtag">#$1</button>');
}

onHashtagClick(hashtag:string) {
    console.log(hashtag);
}

这导致以下描述:

Listening to the rain, falling on the streets <button (click)="onHashtagClick(Rain)" class="hashtag">#Rain</button> <button (click)="onHashtagClick(Chill)" class="hashtag">#Chill</button>

但是当我将它放入我的 HTML 中时,该元素显示如下:

按钮的 HTML 标记按字面意思打印在屏幕上。我发现在 Angular 中,我需要为此使用 [innerHTML] 标签,所以我的 HTML 变成了:

<label class="description" [innerHTML]="description"></label>

但这导致原始文本在主题标签周围没有任何 HTML 标签:

如何制作主题标签的按钮(无超链接)。请让男人知道我做错了什么?!

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

    如果你真的需要按钮,我会创建一个按钮数组并使用 ngFor 来显示按钮列表。

    首先: 创建一个按钮数组

    public buttons:Array<string> = [];
    

    第二:用正则匹配从字符串中提取按钮。

    this.description.match(/#(\w+)/g).forEach((e) => {
        buttons.push(e);
    });
    

    第三:使用 *ngFor 显示按钮

    <button *ngFor="let i of buttons" (click)="onHashtagClick(i)">{{i}}</button>
    

    【讨论】:

      【解决方案2】:

      当你创建一个按钮时,你需要使用单向绑定语法

      而不是

      <button class="hashtag" onclick="onHashtagClick($1)">#$1</button>
      

      你这样写你的点击函数:

      '<button class="hashtag" (click)="onHashtagClick($1)">#$1</button>
      

      还有你说“这里是 HTML:”的地方什么也没有。

      【讨论】:

      • 当我像你说的那样使用它时:this.description = this.description.replace(/#(\w+)/g, '&lt;button class="hashtag" (click)="onHashtagClick($1)"&gt;#$1&lt;/button&gt;');.... 描述仍然是没有任何按钮的全文
      • 当我为它制作一个外部标签而不是一个按钮并添加(click) 属性时,主题标签被label 标签包围,但整个(click) 属性在html???
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2012-01-01
      • 1970-01-01
      相关资源
      最近更新 更多