html - Angular 2在组件继承模板中包含组件html

标签 html angular templates

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

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

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

编辑:

在此示例中存在我的问题:

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

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

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

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

最佳答案

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

希望这有帮助

关于html - Angular 2在组件继承模板中包含组件html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47773136/

相关文章:

javascript - Facebook OG 不显示(分享帖子时)

angular - 如何在 angular4 应用程序中制作 md-sidenav-container 全高 div?

c++ - 如何创建类模板数组?

c++ - 数组作为模板参数 : stack or heap?

html - 带有 HTML5 源属性编解码器的 MIME 类型的完整列表在哪里?

html - 在 html 中转义美元符号

javascript - 无法在本地 html 文件中的 webview 中加载谷歌地图

angular - 从 Angular 项目中 TypeLITE 生成的多级命名空间导入 TypeScript 枚举

以 DD-MM-YYYY 格式将 Angular 返回日期到 formControl MatDatePicker

php - 使用 smarty 编译 product.tpl 时出错