[英]Is this the right usage of ng-container?
我有一個帶有子ShareButton
組件的Product
組件:
<app-product>
<app-share-button (click)="click($event)"></app-share-button>
</app-product>
當我單擊ShareButton
,它通過click($event
)` 將數據返回給父組件:
public click($event) {
this.typeAction = $event.type;
}
像這樣在父組件中使用ng-container
是個好主意嗎:
<app-product>
<app-share-button (click)="click($event)"></app-share-button>
<ng-container [ngIf]="typeAction === 'new'">
<app-new [type]="1"></app-new>
<app-new [type]="2"></app-new>
</ng-container>
<ng-container [ngIf]="typeAction === 'new'">
<app-exist [type]="1"></app-exist>
<app-exist [type]="2"></app-exist>
</ng-container>
</app-product>
這應該簡化還是這是ng-container
的有效用例?
只要它服務於一個目的, ng-container
使用就沒有真正的錯誤。 它所做的只是在 HTML 中提供一個元素,您可以對其進行有角度的操作,但實際上不會呈現到頁面上。
話雖如此,如果您的目標是讓app-new
元素和app-exist
元素成為兄弟元素,這絕對是正確的用法。
但是讓我指出,您可能最好使用*ngIf="condition"
的ngIf速記符號。 *
表示它是一個結構指令,它讓 angular 知道為內部元素使用模板。
這帶來了ng-container
最常見的用例。 由於結構指令可以更改其中的元素,因此每個元素只能有一個。 所以,當你需要有多個結構指令時,你可以將它們嵌套在ng-container
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.