进行Angular内容投影的现代方法是什么?

时间:2018-07-19 19:06:10

标签: angular angular5 angular-material2

我发现了很多老套的方式来进行内容/内容项目,并且我遵循了以下的最新方法(我假设):https://blog.angular-university.io/angular-ng-content/

我正在尝试在另一个组件的模态中包含另一个组件html文件。它们是同级组件,而不是父/子组件,这就是为什么我认为它不起作用。

有人可以引导我朝正确的方向前进吗?

对话框html:

<h1 mat-dialog-title>
    Title here
</h1>

<div mat-dialog-content>
    <ng-content></ng-content>
</div>

<div mat-dialog-actions>
    Actions here
</div>

对话框组件:

import {Component, OnInit}                   from '@angular/core';
import {MatDialog,
    MatDialogRef,
    MAT_DIALOG_DATA}                     from '@angular/material';

@Component({
    selector    : 'test-dialog',
    templateUrl : 'test-dialog.html',
    styleUrls   : ['./test-dialog.scss']
})
export class Test implements OnInit
{
    constructor(public  dialog: MatDialog) {}

    ngOnInit(){}
}

test.html,我要包含的内容:

<test-dialog>
    I want to include this content
</test-dialog>

测试组件:

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

@Component({
    selector    : 'test-component',
    templateUrl : './test.html'
})

export class TestComponent implements OnInit
{

    constructor(public router: Router) {}

    ngOnInit(){}
}

编辑:我还已经将CUSTOM_ELEMENTS_SCHEMA包括在我想包含的模块中

1 个答案:

答案 0 :(得分:0)

我在朋友的帮助下回答了这个问题。

我只是将选择器包含在HTML中,就像放置组件时一样:

<div mat-dialog-content>
    <test-component>
    </test-component>
</div>

区别在于,因为它是同级组件,所以必须导入模块。如果您导入组件,Angular会抱怨您将其导入两次(在对话框模块中一次,在测试模块中一次)。

import {TestModule}       from '../test/test.module';

@NgModule({
    imports: [
        TermsOfServiceModule
    ],

在test.module中,您必须导出组件

exports: [
    TestComponent
],

微妙的细微差别,我希望将来会对别人有所帮助。

相关问题