Angular2 - 将一个组件加载到另一个模板中(作为字符串传递给dynamicaly创建)

时间:2016-12-20 07:31:39

标签: angular typescript

我正在尝试动态创建标题,构建并将标题模板传递为' 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>

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

EXCEPTION: Uncaught (in promise): Error: Template parse errors: 'alert' is not a known element: 1. If 'alert' is an Angular component, then verify that it is part of this module. 2. If 'alert' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message. ("an class="title" style="float: right; margin-right: 10px;"> [ERROR ->]<alert></alert> <img class="notify-circle" src="img/notify_3."): DynamicComponent@4:40

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

问题:

任何人都可以指导我如何使这项工作,将标题模板中的<alert></alert>识别为字符串构造。

如果直接作为模板传递而不是作为字符串传递,

工作正常。

0 个答案:

没有答案