簡體   English   中英

從 DOM 元素中獲取 Angular 組件 class

[英]Get Angular component class from DOM element

我相信這個問題的答案是“否”,但是 Angular 中是否有方法/服務可以傳入組件的根 DOM 節點(例如<foo-component> )並接收組件實例(例如FooComponent )?

我找不到與此相關的 SO 帖子。

例子:

<foo-component id="foo"></foo-component>

const fooElement: HTMLElement = document.getElementById('foo');
const fooInstance: FooComponent = getInstanceFromElement(fooElement);

Angular 中是否有類似getInstanceFromElement的方法?

編輯:

我無法使用ViewChild ... 我正在尋找可以使用的全球服務。 假設我沒有從組件 class 調用此方法。 我很熟悉ViewChild / ContentChild ,它們不是我要找的。 假設我在一個全局注入服務中,並且正在嘗試執行以下操作:

class MyService {
  constructor() {}

  getInstanceFromElement(element: HTMLElement): Component<T> {
    // Is there some special helper service I can use here?
  }
}

試試這樣:

工作演示

模板:

<foo-component #foo></foo-component>

TS:

  @ViewChild('foo', { static: false }) fooComponent: FooComponent;

  ngAfterViewInit() {
    console.log(this.fooComponent)
  }

就在這里。 @ViewChild()是正確的提示。 讓我給你舉個例子:

@ViewChild('editorStepsDomElements', { static: false, read: ElementRef }) fooComponentDomElement: ElementRef;
@ViewChild('fooComponent', { static: false, read: FooComponent }) fooComponent: FooComponent;

所以基本上你可以在ViewChild()中定義你想要得到的東西。 只需將read參數設置為ElementRef (用於獲取 DOM 元素)或您想要獲取的相應組件。

是的,您可以使用動態組件加載器將組件動態附加到 DOM。 按照這個鏈接

這在 Angular 中很簡單。 @ViewChild / @ViewChildren@ContentChild / @ContentChildren默認在ngAfterViewInitngAfterContentInit生命周期中返回組件引用/ QueryList<Component>

例如:

@Component({
  template:`<foo-component></foo-component>`
})
export TestComponent implements AfterViewInit {
  @ViewChild(FooComponent, { static: false }) fooComponent: FooComponent;

  ngAfterViewInit() {
    console.log(this.fooComponent)
  }

對於指令,如果指令指定exportAs ,則可以使用模板變量。 請參閱https://netbasal.com/angular-2-take-advantage-of-the-exportas-property-81374ce24d26以獲得良好的記錄。

暫無
暫無

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

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