如何在Angular 6中将HTML标签或元素附加到div? [英] How to append HTML tags or elements to a div in Angular 6?

查看:370
本文介绍了如何在Angular 6中将HTML标签或元素附加到div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在模板中有一个div,该模板具有#divMessages作为模板引用名称.

I have a div in a template that has #divMessages as a template reference name.

<div  #divMessages></div>

发生某些事件时,我想将HTML标记附加到此div.我以以下方式尝试过,但是HTML标签作为字符串附加了.

When some events occur, I want to append HTML tags to this div. I tried in the following way but HTML tags appended as a string.

this.divMessages.nativeElement.append('<li>'+data.message+ '</li>');

我当前的方法将HTML标记视为字符串. 我如何附加HTML标签,以隐藏标签并仅显示数据. (在上述情况下,仅显示列表项,而标签则隐藏).

My current method considers HTML tags as a string. How I can append HTML tags, to hide the tags and show only the data. (means only list items are shown and the tags are hidden in the above case).

推荐答案

我通过使用Renderer2 Abstract类解决了这个问题,该类是Angular提供的用于处理DOM元素的服务. 从角铁芯导入Renderer2.然后创建元素并向其添加文本.

I solved this problem by using the Renderer2 Abstract class, Which is a service provided by Angular to Manipulate DOM elements. Import the Renderer2 from angular core. then create element and append text to it.

  import {Component, OnInit,NgModule, Renderer2 } from '@angular/core';

将Renderer2对象传递给类constructur.

pass Renderer2 object to class constructur.

constructor(private http: HttpClient,private renderer:Renderer2) { }

//create the DOM element 
let li=this.renderer.createElement('li');

//create text for the element
const text = this.renderer.createText(data.message);

//append text to li element
  this.renderer.appendChild(li, text);

//Now append the li tag to divMessages div
this.renderer.appendChild(this.divMessages.nativeElement,li);

我使用@ViewChild装饰器将div作为divMessages

i used @ViewChild decorator to get the div as a divMessages

 @ViewChild("divMessages", {read: ElementRef}) private divMessages: ElementRef;

这篇关于如何在Angular 6中将HTML标签或元素附加到div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆