网站搜索

angular - Angular2 - 让一个组件加载到不同的模板中(作为字符串传递以动态创建)


我正在尝试动态创建一个标题,将标题模板构建并作为'string'传递给我的动态组件,该组件会编译并加载标题。我的要求是在标题组件模板字符串中调用另一个组件并加载它。

header.component.ts:

import { Component, OnInit, Input } from '@angular/core';

import { AlertComponent } from './alert.component';

@Component({
    selector: 'header', 
    template: `<html-outlet [html]="value"></html-outlet>`,
})
export class HeaderComponent implements OnInit {

@Input()
header = Object;
@Input()
headerData = Object;
headerObj = new Array<any>();
property = new Array<any>();
dataObj = new Array<any>();
dataProperty = new Array<any>();
value: string;

ngOnInit() {
    this.headerObj = JSON.parse(JSON.stringify(this.header));
    this.dataObj = JSON.parse(JSON.stringify(this.headerData));
    this.value = this.prepareHeaderHtml();
}


prepareHeaderHtml(): string {
    this.dataProperty = this.dataObj;
    let user = this.dataProperty[0]["username"];
    console.log("username : "+ user)
    this.property = this.headerObj;
    let headerTemplate = '<div class="header">';
    for (let headerValues in this.property) {
        let headerValue = this.property[0]["value"];
        headerTemplate += `<ul>
                                <span class="fa fa-home"></span>&nbsp;
                                ${headerValue}
                                <span class="title" style="float: right; margin-right: 10px;">
                                    <alert></alert>
                                    <img class="notify-circle" src="img/notify_3.png">&nbsp; ${user} &nbsp;
                                    <img class="user-circle" src="img/profile.png"></span>
                        </ul>`;
    }
    headerTemplate += '</div>';
    return headerTemplate
}

}

alert.component.ts:

import { Component } from '@angular/core';

@Component({
    selector: 'alert',
    template: `<span><img class="alert-circle" src="img/alert_3.png">&nbsp;</span>`,     
})
export class AlertComponent {}
}

当我将头模板字符串传递给动态组件类时

<html-outlet [html]="value"></html-outlet>

我在浏览器控制台收到如下错误:

异常:未捕获(在 promise 中):错误:模板解析错误:'alert' 不是已知元素:1. 如果 'alert' 是 Angular 组件,请确认它是此模块的一部分。2. 如果 'alert' 是 Web 组件,则将 "CUSTOM_ELEMENTS_SCHEMA" 添加到此组件的 '@NgModule.schemas' 以抑制此消息。("an class="title" style="float: right; margin-right: 10px;"> [错误 ->]<alert></alert> <img class="notify-circle" src="img/notify_3."):DynamicComponent@4:40

已经在 app.modules.ts 中定义并导入了 AlertComponent,以及 MenuComponent 和 HtmlOutlet。还在动态构建组件中导入了 AlertComponent。

问题:

有人能指导我如何使这个工作,让 <alert></alert> 在作为字符串构建的头模板中被识别吗。

如果直接作为模板传递而不是作为字符串传递的话,虽然可以正常工作。