錯誤百科

水合不支援 DOM 節點的投影

此錯誤表示在伺服器端序列化過程中,Angular 遇到了在 Angular 情境之外建立的節點(也就是使用原生 DOM API 建立),並發現這些節點被作為可投影節點提供。它們很可能是透過 ViewContainerRef.createComponent 或 createComponent API 提供的。Angular 水合不支援這種使用方式。

更多關於水合的資訊,請見本指南。

以下範例會觸發此錯誤。

@Component({
  selector: 'dynamic',
  template: `<ng-content />`,
})
class CardWrapper {}

@Component({
  selector: 'app',
  template: `<div #target></div>`,
})
class DynamicCard {
  @ViewChild('target', {read: ViewContainerRef}) vcr!: ViewContainerRef;
  envInjector = inject(EnvironmentInjector);

  ngAfterViewInit() {
    const div = document.createElement('div');
    const p = document.createElement('p');
    // In this test we create DOM nodes outside of Angular context
    // (i.e. not using Angular APIs) and try to content-project them.
    // This is an unsupported pattern and an exception will be thrown.
    const compRef = createComponent(CardWrapper, {
      environmentInjector: this.envInjector,
      projectableNodes: [[div, p]],
    });
  }
}

除錯方式

開發者主控台中的錯誤訊息應包含造成問題的應用程式 DOM 結構特定部分的資訊。請檢查該部分的應用程式是否有與水合相關的錯誤,例如使用原生 API 直接操作 DOM。

你可以把 ngSkipHydration 屬性加到元件宿主節點,作為可能的暫時解法。