簡體   English   中英

ng-template 中的組件初始化

[英]Component initialization in ng-template

我正在使用ng-content將一個 Angular 組件包裝在另一個組件中。 外部組件應該完全控制內部組件何時呈現。 但是,我遇到了一個我不明白的情況。 外部組件使用如下模板(簡化版):

<ng-template>
  <ng-content></ng-content>
</ng-template>

根據我的理解,內容根本不應該被渲染,因為它包含在ng-template 在這個示例 stackblitz 中,您可以看到內部組件沒有被渲染,但它仍然被初始化。 內部組件的 OnInit 中的控制台日志仍然顯示在控制台中。

我的問題是:

  • 為什么會發生這種情況?
  • 在這種情況下如何避免組件初始化?

Angular 文檔有關於結構指令的信息:它只是渲染或不渲染模板, - 沒有關於加載內部組件的詳細信息。

其次,您將已經編譯和渲染的對象傳遞給ng-content

如果你想lazy加載模板,只需傳遞模板:

<app-outer>
  <ng-template>
    <app-inner></app-inner>
  </ng-template>
</app-outer>

外部組件.html

<ng-content></ng-content>
<ng-template [ngTemplateOutlet]="template"></ng-template>

外部組件.ts

@Component({
  selector: 'app-outer',
  templateUrl: './outer.component.html'
})
export class OuterComponent {
  @ContentChild(TemplateRef) template: TemplateRef<unknown>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM