錯誤百科

元件 ID 產生衝突

建立元件時,Angular 會為每個元件產生唯一的元件 ID。這個 ID 是使用 Angular 元件的中繼資料產生的,包括但不限於:選擇器、宿主繫結的數量、類別屬性名稱、檢視查詢與內容查詢。當兩個元件的中繼資料完全相同(通常是共用同一個選擇器)時,就會發生 ID 產生衝突。

元件 ID 在 Angular 內部用於:

為了避免元件 ID 衝突可能造成的問題,建議依照下述方式解決。

元件 ID 衝突範例

@Component({
  selector: 'my-component',
  template: 'complex-template',
})
class Some {}

@Component({
  selector: 'my-component',
  template: 'empty-template',
})
class SomeMocked {}

定義這兩個元件會觸發 ID 產生衝突,並在開發期間顯示警告。

除錯方式

警告訊息包含 ID 互相衝突的兩個元件的類別名稱。

可以使用以下其中一種解法來解決此問題:

  1. 變更兩個元件其中之一的選擇器。例如使用像 :not() 這樣沒有效果的偽選擇器,搭配不同的標籤名稱。

    @Component({
      selector: 'my-component:not(p)',
      template: 'empty-template',
    })
    class SomeMocked {}
  2. 在其中一個元件上加上額外的宿主屬性。

    @Component({
      selector: 'my-component',
      template: 'complex-template',
      host: {'some-binding': 'some-value'},
    })
    class Some {}