在Angular中ng-content和ng-template有什么作用?

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

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

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

回答

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。


以上是在Angular中ng-content和ng-template有什么作用?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>