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

时间:2017-12-12 12:51:47

标签: html angular templates

我有一个带有html / ts文件的组件A.当我从A继承第二个组件B时,这将采用第一个组件的所有属性和方法。如果我想使用组件A html,我可以在 $("#myUploadForm").submit(function (e) { e.preventDefault(); var fd = new FormData(this) $.ajax({ url: '/Admin/AddProduct', type: 'POST', data: fd, contentType: false, cache: false, processData:false }) }) 属性中引用comp A html。

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

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

修改

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

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

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

  1. 将所有需要在所有继承组件中使用的属性更改为输入并注入
  2. 重复的HTML代码
  3. 找到一种方法来引用第一个组件的html而不创建它的实例。
  4. 我认为最好的解决方案是第三种。但我不知道如何做到这一点..

1 个答案:

答案 0 :(得分: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

希望这有帮助

相关问题