有兩個以上的元件使用相同的元素選擇器。由於一個元素只能關聯到單一元件,選擇器必須是唯一的字串,Angular 才不會產生歧義。
這個錯誤在執行階段發生於以下情況:你把兩個選擇器套用到單一節點上,而兩者各對應到不同的元件;或是你把單一選擇器套用到某個節點上,而它對應到一個以上的元件。
import {Component} from '@angular/core';
@Component({
selector: '[stroked-button]',
templateUrl: './stroked-button.html',
})
export class StrokedBtn {}
@Component({
selector: '[raised-button]',
templateUrl: './raised-button.html',
})
export class RaisedBtn {}
@Component({
selector: 'app-root',
template: `
<!-- This node has 2 selectors: stroked-button and raised-button, and both match a different component: StrokedBtnComponent, and RaisedBtnComponent , so NG0300 will be raised -->
<button stroked-button raised-button></button>
`,
})
export class App {}
如何除錯
使用錯誤訊息中的元素名稱,搜尋你的程式碼庫中使用了相同選擇器宣告的位置:
@Component({
selector: 'YOUR_STRING',
…
})
請確保每個元件都有唯一的 CSS 選擇器。這樣才能保證 Angular 會渲染出你預期的元件。
如果你難以找出使用這個選擇器標籤名稱的多個元件,請檢查從匯入的元件庫(例如 Angular Material)來的元件。並請確保你的選擇器有遵循最佳實務,以避免發生衝突。