简体   繁体   English

如何从 Angular 组件中的变量显示 HTMLElement?

[英]How to display a HTMLElement from a variable in an Angular component?

I store a dynamically generated HTMLElement in a variable in my component class.我将动态生成的HTMLElement存储在组件 class 的变量中。 I would like to display it, but I have no idea how is that possible.我想展示它,但我不知道这怎么可能。 I tried it like this:我试过这样:

Inside the component class:在组件 class 内部:

elem: HTMLElement;

In the template:在模板中:

<ng-container *ngTemplateOutlet="elem"></ng-container>

I get this error:我收到此错误:

TypeError: templateRef.createEmbeddedView is not a function

If you have a naked HTMLElement , there's nothing Angular-y you can do.如果您有一个裸HTMLElement ,那么您无能为力。 NgTemplateOutlet expected a TemplateRef , not a vanila HTMLElement object. NgTemplateOutlet需要一个TemplateRef ,而不是一个普通的HTMLElement object。

To insert an HTML Element into the DOM, simply use the appropriate DOM method for that.要将 HTML 元素插入 DOM,只需使用适当的 DOM 方法即可。 Which one you'll use entirely depends on the place where you want to use it.您将使用哪一个完全取决于您要使用它的地方。

For example, you could do例如,你可以做

const wrapper = document.querySelector('div.wrapper')
wrapper.append(el) // pass in your element

You can also grab the reference to the wrapper in a more Angular way, by adding an Angular reference in the template on the element you want to select,您还可以通过在模板中添加 Angular 引用来以更 Angular 的方式获取对包装器的引用,方法是在您想要 select 的元素上,

<div class="wrapper" #wrapper></div>

and using ViewChild decorator on a property where you want Angular to assign the ElementRef to.并在您希望 Angular 将ElementRef分配给的属性上使用ViewChild装饰器。

@ViewChild('wrapper', { static: true, read: ElementRef })
public wrapperElRef: ElementRef<HTMLDivElement>

Once the view is initialized (you'll be notified when this happens via the ngAfterViewInit hook), you can grab the HTML element within by accessing `.nativeElement:一旦视图被初始化(当发生这种情况时你会通过ngAfterViewInit钩子得到通知),你可以通过访问 `.nativeElement 来获取 HTML 元素:

this.wrapperElRef.nativeElement //: HTMLDivElement

You can now do你现在可以做

this.wrapperElRef.nativeElement.append(elem)

That said, unless you know what you're doing (usually wrapping an existing library or integrating with an existing large system that you cannot yet refactor completely)也就是说,除非您知道自己在做什么(通常包装现有库或与您还不能完全重构的现有大型系统集成)

Most of the times it depends how you have created the html.大多数情况下,这取决于您如何创建 html。 I suggest specifying in comments where are you receiving the variable which holds the HTMLElement , so I could give you the most effective way to do it.我建议在注释中指定您在哪里接收包含HTMLElement的变量,以便我可以为您提供最有效的方法。

But generally - try using innerHTML binding in the parent element.但通常 - 尝试在父元素中使用innerHTML绑定。

Typescript: Typescript:

public elem: HTMLElement;

public getElement(): string {
   return this.elem.innerHTML;
}

HTML: HTML:

<div innerHTML="getElement()"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM