首页 > 解决方案 > 在 Angular 中 ng-content 和 ng-template 做什么?

问题描述

我试图弄清楚这 2 做了什么,我有点困惑,它们是像 div 还是类似的东西?

我阅读了文档,但不清楚是的,我也想知道什么时候应该使用它们?还是为了什么?

顺便说一句,我可以将 css 应用于他们两个吗?

标签: angularmean-stackng-templateangular2-ngcontent

解决方案


ng-content用于在组件内的特定位置投影内容。

例子:

<!-- custom.component.html -->
<h1>
  <ng-content></ng-content>
</h1>
<!-- app.component.html -->
<app-custom>test</app-custom>

上面的代码将生成以下 html:

<app-custom>
  <h1>
    test
  </h1>
</app-custom>

ng-template是描述模板的块,除非明确引用或使用模板,否则不会呈现模板。

以下代码不输出任何 HTML:

<ng-template>
  <div>Hello</div>
</ng-template>

但是这个会显示div

<ng-container *ngIf="false; else myTemplate"></ng-container>
<ng-template #myTemplate>
  <div>Hello</div>
</ng-template>

两者都不会在 HTML 代码中可见,它们仅由 Angular 使用。


奖金:

ng-container是另一个与结构指令(ngFor、ngIf)一起使用的 Angular 元素,它也不会生成 HTML。


推荐阅读