我有一个组件 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
属性。我找到了三个解决方案:
- 更改所有继承组件中需要使用的所有属性以输入和注入(inject)
- 重复的 html 代码
- 找到一种方法来引用第一个组件的 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>
希望这有帮助
关于html - Angular 2在组件继承模板中包含组件html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47773136/