錯誤百科

多個元件符合相同元素

在編譯範圍內,有兩個以上的元件符合範本中的相同元素。 由於 Angular 只能把一個元件關聯到指定元素,選擇器必須夠獨特以避免歧義。

NOTE: 這是執行時期錯誤 NG0300: Selector Collision 的建置時期對應版本。在編譯時期偵測到它,表示錯誤會立即浮現。

import {Component} from '@angular/core';

@Component({
  selector: '[stroked-button]',
  template: '',
})
export class StrokedBtn {}

@Component({
  selector: '[raised-button]',
  template: '',
})
export class RaisedBtn {}

@Component({
  selector: 'app-root',
  // NG8023: StrokedBtn and RaisedBtn both match this element.
  template: `<button stroked-button raised-button></button>`,
  imports: [StrokedBtn, RaisedBtn],
})
export class App {}

除錯方式

使用錯誤訊息中的元素名稱,搜尋你的程式碼中使用相同選擇器宣告的地方:

@Component({
  selector: 'YOUR_STRING',
…
})

確保每個元件都有唯一的 CSS 選擇器。這將保證 Angular 渲染你預期的元件。

如果你難以找到具有此選擇器標籤名稱的多個元件,請檢查從匯入的元件程式庫(例如 Angular Material)來的元件。請確保你遵循選擇器的最佳實踐,以避免衝突。