[英]How to call a component inside component TS in angular
當我通過另一個組件中的函數將其顯示時,我無法顯示該組件。
這是我的代碼(主要組成部分):
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-body',
templateUrl: './body.component.html'
})
export class BodyComponent implements OnInit{
dtOptions: DataTables.Settings = {};
customizing() {
let html = `<app-button></app-button>`;
console.log("ingresa");
var element = document.getElementsByClassName("personalizado");
element[0].innerHTML=html;
}
ngOnInit() {
let scope = this;
this.dtOptions = {
dom: "<'row'"+
"<'.extra-elements personalizado'>"+
"<'.extra-elements'<li>>>"+
"<'row'<'.col-12'<t>>>"+
"<'row'<'.col-12'p>>",
pagingType: 'full_numbers',
initComplete: function(settings, json) {
scope.personalizado();
}
};
}
我在customizing()函數中調用<app-button> <./ app-button> ,並使用innerHTML將所有app-button包含在內。 那是行不通的,沒有編譯應用程序按鈕,並且渲染后的視圖僅在簡單標簽中顯示dom中的標簽。
這是應用程序按鈕組件:
<div class='col'><button type='button' class='btn btn-dark'>Clicked</button></div>
換句話說,DOM像標簽一樣顯示app-button而不編譯按鈕HTML。
有辦法嗎?
模板需要被編譯,您不能將組件選擇器注入html,然后期望它被呈現。 您可以使用ngIf或ngFor有條件地渲染組件。
在./body.component.html中
<app-button *ngIf="conditionToShowButton">Button Text</app-button>
要么
<app-button *ngFor="let btn of btns">{{btn.text}}</app-button>
有關按鈕的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.