*ngTemplateOutlet is used for two scenarios — to insert a common template in various sections of a view irrespective of loops or condition and to make a highly configured component.
将同一個 template 插入到一個視圖不同的 sections 中。
例如,将 id 為 compantLogoTemplate 的模闆,插入到同一個視圖的不同位置去。也就是說,ngTemplateOutlet 的值是模闆 id, 用 # 辨別。
![](https://img.laitimes.com/img/__Qf2AjLwojIjJCLyojI0JCLicmbw5SZ1IGZwQDOzcTNwYmNzMTY3ImN0UTOiZDOjRGNygzN58CX5d2bs92Yl1iclB3bsVmdlR2LcNWaw9CXt92Yu4GZjlGbh5yYjV3Lc9CX6MHc0RHaiojIsJye.png)
這裡 ngTemplateOutlet 傳入的值不再是寫死的模闆 id ,而是 Component 屬性 headerTemplate, bodyTemplate和 footerTemplate.
這些值需要消費者傳入,是以在 Component 裡定義 headerTemplate,bodyTemplate 等等時,需要加上@Input 的注解。
Angular ngTemplateOutlet和 ng-content 的差別
參考文獻:Everything you need to know about ng-template, ng-content, ng-container, and *ngTemplateOutlet in Angular
二者都能幫助 Angular 開發者實作高度可定制化的Component.
ng-content 隻是簡單地将消費者傳入的内容進行顯示。無法使用 ng-content 進行形如 ngTemplateOutlet 那樣的條件渲染。
You have to show the content that is received from the parent with no means to make decisions based on the content.