[英]How to call a component inside component TS in angular
I can't show a component when I put it through a function in another component. 当我通过另一个组件中的函数将其显示时,我无法显示该组件。
This is my code(main component): 这是我的代码(主要组成部分):
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();
}
};
}
I call < app-button ><./app-button> in the function customizing() and put all the contain of app-button using innerHTML. 我在customizing()函数中调用<app-button> <./ app-button> ,并使用innerHTML将所有app-button包含在内。 Thats not work, app-button is not compiled and the renderised show the tag in dom but only like a simple tag. 那是行不通的,没有编译应用程序按钮,并且渲染后的视图仅在简单标签中显示dom中的标签。
This is the app-button component: 这是应用程序按钮组件:
<div class='col'><button type='button' class='btn btn-dark'>Clicked</button></div>
In other words, The DOM show app-button like a tag and not compiled the button HTML. 换句话说,DOM像标签一样显示app-button而不编译按钮HTML。
Are there a way to do that? 有办法吗?
Templates need to be complied, you can't inject a components selector into the html and then expect it to be rendered. 模板需要被编译,您不能将组件选择器注入html,然后期望它被呈现。 You can either use ngIf or ngFor to conditionally render components. 您可以使用ngIf或ngFor有条件地渲染组件。
in ./body.component.html 在./body.component.html中
<app-button *ngIf="conditionToShowButton">Button Text</app-button>
or 要么
<app-button *ngFor="let btn of btns">{{btn.text}}</app-button>
For a list of buttons. 有关按钮的列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.