簡體   English   中英

renderer2 selectRootElement() 不匹配任何元素

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

我正在創建一個小網頁,它需要在 div 中使用動態創建的元素。 我想在 .ts 文件中呈現按鈕,但我得到了

ERROR 錯誤:選擇器“myDIV”不匹配任何元素

這是在 .ts 文件中添加簡單文本的示例:

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

.html 文件:

<div id="myDIV"> 

</div>

問候

你做錯了,在 html 模板中定義你的動態元素,例如

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

其中myTextshowButtonshowText是 .ts 文件中定義的組件字段。 <ng-container>放置內容(文本)而不創建 html 元素(如 div/span)

如果要使用多個元素 - 將一個元素定義為單獨的組件並在父組件 html 模板中使用它,如下所示

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

其中elementsDataArray是在父 .ts 文件中定義的數組,其中包含對象(項目),其中包含在 myElement 組件中使用的數據並綁定到其參數data

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM