ng-template、ng-container、ng-content和ngTemplateOutlet、ngProjectAs傻傻分不清!他们究竟是干啥的???
一句話描述5個關鍵詞的作用:
ng-template是備胎(模板):通常在html里面作為備用模板,當綁定了對應的#標記的時候才會顯示
ng-container是舔狗(虛擬標簽):包裹的內容顯示,而自身標簽不會出現在html中
ng-content是替身(替代組件包裹內容、插槽):通常出現在子組件中,用于替代父組件中><尖括號包裹的內容,并在子組件對應的ng-content位置渲染
ngTemplateOutlet是渣女的閨蜜(指向綁定的模板):讓舔狗去做備胎就做備胎,做什么樣的備胎就綁定對應的ng-template引用#標記
ngProjectAs是偽裝獸:把標簽匿名成其他名稱被ng-content的select獲取
接下來就用一個綜合的例子講解這5者分別的用處
[ngTemplateOutlet]等同于*ngTemplateOutlet,以下幾種寫法是等效的:
? <ng-container [ngTemplateOutlet]="myTemplate" ></ng-container>
? <ng-container *ngTemplateOutlet="myTemplate"></ng-container>
? <div?[ngTemplateOutlet]="myTemplate" ></div><!--這里的div可以換成任意標簽-->
? <div *ngTemplateOutlet="myTemplate"></div><!--這里的div可以換成任意標簽-->ng-content就是把父組件中,插入子組件倆尖括號夾住的html內容部分替代作為一個占位符使用,這里ng-content還有一個select屬性可以分節點替代類似vue插槽的功能
父組件app.component.html代碼
<app-home><ng-container [ngTemplateOutlet]="myTemplate" ></ng-container><hr><ng-container *ngTemplateOutlet="myTemplate"></ng-container><h1>這是個大標題</h1><hr><h2 class="small-title">這是個小標題</h2><hr><h3 ngProjectAs="sub-title">這是個副標題</h3></app-home><!-- 模板---------------------------------------- -->
<ng-template #myTemplate><b>這里是模板文字</b>
</ng-template>
子組件app-home.component.html代碼
<ng-content select='sub-title'></ng-content>
<hr>
<ng-content select='.small-title'></ng-content>
<hr>
<ng-content select='h1'></ng-content>
<br>
<ng-content></ng-content>
??最終渲染出來html如下
看下圖的對比關系,就明白了這幾個ng標簽(屬性) 有啥作用了
總結
以上是生活随笔為你收集整理的ng-template、ng-container、ng-content和ngTemplateOutlet、ngProjectAs傻傻分不清!他们究竟是干啥的???的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 设置VSCode Git签出分支快捷键A
- 下一篇: 设置VSCode刷新资源管理器快捷键Ct