【问题标题】:Angular 2 include component html in a component inherited templateAngular 2 在组件继承的模板中包含组件 html
【发布时间】:2017-12-12 12:51:47
【问题描述】:

我有一个带有 html/ts 文件的组件 A。当我从 A 继承第二个组件 B 时,这将采用第一个组件的所有属性和方法。如果要使用组件A html,可以在templateUrl属性中引用comp A html。

我有问题。我想使用组件 A html,但我想扩展它。所以我的想法是将第一个组件html“包含”到第二个组件。 Angular2有可能吗?还有其他方法吗?

我不想在组件 B 中创建组件 A 的实例。我只想要 html 标记。

编辑:

在这个例子中有我的问题:

https://stackblitz.com/edit/ng-content-projection-lzjwea

当我继承了 Hello2 ts 时,如果我在 hello2 html 中创建一个 hello 组件的实例,它将获取它的 name 属性。我找到了三个解决方案:

  1. 更改所有继承组件中需要使用的所有属性以输入和注入
  2. 重复的 html 代码
  3. 找到一种方法来引用第一个组件的 html 而无需创建它的实例。

我认为最好的解决方案是第三个。但我不知道怎么做..

【问题讨论】:

  • ng-content(内容投影)是否适合您?
  • 很遗憾没有。我创建了一个示例来向您展示主要帖子中的问题

标签: html angular templates


【解决方案1】:

ng-content 可用于在组件中投影动态内容。

例如,考虑以下情况

hello.component.html

<div id='border'>
    <h1>Base Component</h1>
    <p>ng-content could be used for projecting dynamic content within a component</p>
    <ng-content>
        <!-- Dynamic content goes here -->
    </ng-content>
</div>

所以,现在无论介于两者之间的是什么

<hello>
    <!-- dynamic html here -->
</hello>

app.component.html

<hello>
  <div style="border: 2px solid red">
    <h2>Child Component</h2>
    <button id="sample1"> Sample 1 </button>
    <button id="sample2"> Sample 2 </button>
  </div>
</hello>

Example

希望对你有帮助

【讨论】:

  • 我知道 ng-content,但无法解决我的问题。我创建了一个示例来向您展示我的问题。这是主要问题。
猜你喜欢
  • 2018-04-20
  • 2017-08-06
  • 1970-01-01
  • 2017-03-12
  • 2017-10-18
  • 1970-01-01
  • 2019-06-17
  • 2016-11-13
  • 2018-01-16
相关资源
最近更新 更多