【问题标题】:Add Custom Template Html in Component Selector在组件选择器中添加自定义模板 Html
【发布时间】:2018-01-23 06:45:51
【问题描述】:

有没有办法在组件选择器中添加自定义模板 html?

我有一个带有选择器<app-toolbar> 的组件AppToolbarComponent,它有一个空白模板。我想在两个不同的组件上使用这个组件,但是在使用组件时定义了模板。例如:

开启page-one.component.html:

<app-toolbar>
    <button (click)="onClickOne()">Button in Component One</button>
</app-toolbar>

... 以及 page-two.component.html:

<app-toolbar>
    <button (click)="onClickTwo()">Button in Component Two</button>
</app-toolbar>

有什么想法吗?

【问题讨论】:

  • 你试过使用&lt;ng-content&gt;吗?
  • @pixelbits 太棒了!不知道,我正在尝试&lt;ng-template&gt;。像魅力一样工作(Y)谢谢。

标签: angular


【解决方案1】:

根据 @pixelbits 的评论,这是一个答案:

&lt;app-toolbar&gt;中,在组件模板中添加&lt;ng-content&gt;。这是一个例子:

<div>Some Content</div>
<ng-content></ng-content>

现在,在&lt;app-toolbar&gt; 选择器中添加的任何内容都将在&lt;ng-content&gt; 中呈现。例如:

<app-toolbar>
    <!-- The following content will render inside <ng-content> 
         in the app-toolbar component -->
    <button (click)="onClickOne()">Button in Component One</button>
</app-toolbar>

这是StackBlitz Demo 的链接。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-15
    • 2016-04-01
    • 2017-10-20
    • 2013-01-25
    相关资源
    最近更新 更多