angular - 在 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 - Angular,2个模块的错误声明,如何解决?
- objective-c - How to access and initialize components of simd types?
- spring - WebSecurityConfig http.logout().addLogoutHandler 不工作
- google-app-engine - Connecting to bank account with OAuth2.0 and Google App Scripts
- jsf - faces-redirect 使用 http 而不是 https
- angular - How can read an excel file which is in the assets folder- Angular?
- python - If Statment in Python while Scraping
- javascript - ReactDOM - 元素类型无效:需要一个字符串(对于内置组件)或一个类/函数(对于复合组件)但得到:未定义
- http2 - 了解 HTTP2 服务器推送和多路复用
- selenium - 无法通过 selenium webdriver 访问打印按钮,因为它位于 shadow-root 中