简体   繁体   English

renderer2 selectRootElement() 不匹配任何元素

[英]renderer2 selectRootElement() did not match any elements

I am creating a little webpage which needs to use dynamically created element inside the div.我正在创建一个小网页,它需要在 div 中使用动态创建的元素。 I want to render buttons in .ts file but I am getting我想在 .ts 文件中呈现按钮,但我得到了

ERROR Error: The selector "myDIV" did not match any elements ERROR 错误:选择器“myDIV”不匹配任何元素

Here's the example adding simple text in .ts file:这是在 .ts 文件中添加简单文本的示例:

  renderButtons(){
    const element = this.renderer.selectRootElement('myDIV');
    const text = this.renderer.createText('something');
    this.renderer.appendChild(element, text); 
  }

.html file: .html 文件:

<div id="myDIV"> 

</div>

Regards问候

You do it in wrong way, define your dynamic elements INSIDE html template eg你做错了,在 html 模板中定义你的动态元素,例如

<div id="myDIV"> 
    <button *ngIf="showButton==true">myButton</button>
    <ng-container *ngIf="showText==true">{{ myText }}</ng-container>
</div>

where myText , showButton and showText are fields of component defined inside .ts file.其中myTextshowButtonshowText是 .ts 文件中定义的组件字段。 The <ng-container> put content (text) without creating html element (like div/span) <ng-container>放置内容(文本)而不创建 html 元素(如 div/span)

If you want to use many elements - define one element as separate component and use it in parent component html template as follows如果要使用多个元素 - 将一个元素定义为单独的组件并在父组件 html 模板中使用它,如下所示

<myElement *ngFor="let item in elementsDataArray" [data]="item"></myElement>

where elementsDataArray is array defined in parent .ts file, which contains objects (items) with data used in you myElement component and bind to its parameter data .其中elementsDataArray是在父 .ts 文件中定义的数组,其中包含对象(项目),其中包含在 myElement 组件中使用的数据并绑定到其参数data

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

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