簡體   English   中英

角度錯誤選擇器不匹配任何元素

[英]Angular Error The selector did not match any elements

在Angular 5組件中,出現錯誤: Error: The selector "#person-component" did not match any elements. 事實是,當我檢查頁面時,該元素在那里具有正確的ID。 另外,當我從路由器鏈接加載頁面時,它可以工作,只有當我直接導航到URL時,我才會收到錯誤消息。

它找不到的元素是由另一個組件添加的,我正在將其添加到包含父組件的模塊中。 顯然,當我使用來自主要組件的鏈接時,正在發生一些不同的事情,但是我不知道那是什么。 失敗的行(在下面)在ngAfterContentInit ,所以我不知道為什么它找不到元素。

這是組件中失敗的代碼:

ngAfterContentInit () {
    ...
    const container = this.renderer.selectRootElement('#person-component');
    this.renderer.setAttribute(container, 'id', htmlId);
    ...
  }

這是添加方式。

主要組件HTML:

<employee-component> ...  </employee-component>

子組件:

@Component({
...
selector: 'employee-component',
template: `
    <div id="person-component"></div>
`,
})

這是檢查頁面時的元素:

<div id="person-component"></div>

演示

使用ngAfterViewInit而不是ngAfterContentInit

  ngAfterViewInit () {

    const container = this.r.selectRootElement('#person-component');
    this.renderer.setAttribute(container, 'id', htmlId);

  }

我們使用ngAfterContentInit等待<ng-content>預計內容被加載。

暫無
暫無

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

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