【问题标题】:What is the modern way to do Angular content projection?进行 Angular 内容投影的现代方法是什么?
【发布时间】:2018-07-20 07:42:48
【问题描述】:

我找到了很多旧方法来转换/内容项目,我遵循了最新的方法(我假设)在这里找到: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 包含在我想要包含的模块中

【问题讨论】:

  • 那么test组件的标记是什么?
  • @Antoniossss 这是一个很长的合法 HTML 文件 :)
  • 那又如何,它与问题有关。您在dialog 中显示的内容应该是您的测试标记
  • 看看 Angular Elements angular.io/guide/elements - 它们可能对你有用。
  • @Antoniossss,回答您的问题 - 是的,我相信单独使用 ng-content 与使用为自定义元素提供的框架 Angular 是有区别的。你不是吗?我承认有一些重叠,但我不会说它们是同一件事。

标签: angular angular5 angular-material2


【解决方案1】:

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

我只是将选择器包含在 HTML 中,就像您在放置组件时所做的那样:

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

不同之处在于它是同级组件,您必须导入模块。如果你导入组件,Angular 会抱怨你导入了两次(一次在对话框模块中,一次在测试模块中)。

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

@NgModule({
    imports: [
        TermsOfServiceModule
    ],

在 test.module 中你必须导出组件

exports: [
    TestComponent
],

有点棘手的细微差别,我希望将来对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-30
    • 2023-03-23
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-21
    相关资源
    最近更新 更多