1

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

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

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

4

2 回答 2

12

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。

于 2020-11-28T19:09:31.443 回答
3
  1. <ng-template>

顾名思义,<ng-template> 是 Angular 与结构指令(、、和自定义指令)一起使用的*ngIf模板*ngFor元素[ngSwitch]

这些模板元素仅在存在结构指令的情况下工作。Angular 将宿主元素(应用指令的对象)封装在内部<ng-template>,并<ng-template>通过将其替换为诊断注释来使用完成的 DOM。

  1. <ng-content>

它们用于创建可配置组件。这意味着可以根据用户的需要配置组件。这就是众所周知的内容投影。已发布库中使用的组件可用于<ng-content>使自己可配置。

于 2020-11-29T00:15:50.477 回答