簡體   English   中英

如何在 Angular 模板中獲取元素引用而不是組件引用

[英]How to get element reference in Angular template instead of component reference

考慮以下模板:

<my-component #ref></my-component>
<my-comp-2 [maxWidth]="ref.clientWidth"></my-comp-2>

我的組件沒有.clientWidth屬性,但托管我的組件的元素本身有。

是否有我可以使用的名稱或其他類似的解決方案來單獨獲取對 HTML 中元素本身的引用? 例如,我想做這樣的事情:

<my-component #ref="element"></my-component>

問題是沒有帶有名為“element”的exportAs選項的指令。 Angular 站點上也沒有記錄任何內置等效項。

我知道我可以將clientWidth添加為屬性,並且我可以通過ElementRef<HTMLElement>和依賴項注入獲得對<my-component> class 中元素的引用,但我想要一個單獨涉及 HTML 的解決方案。 這樣的解決方案存在嗎?

我覺得你的答案是正確的,但出於好奇,你可以努力解決:創建一個像這樣的指令

@Directive({
  selector: '[element-directive]',
  exportAs: 'ngDirective',
})
export class MyDirective {
  constructor(public elementRef: ElementRef){}
}

並使用

<my-component element-directive #ref="ngDirective">
</my-component>
<my-comp-2 [style.max-width]="ref.elementRef.nativeElement.offsetWidth+'px'">
</my-comp-2>

正如您所指出的,另一種方法是在我的組件的構造函數中,注入 ElementRef 並將其公開

constructor(public elementRef:ElementRef){}

然后,您可以使用

<my-comp-2 [style.max-width]="ref.elementRef.nativeElement.offsetWidth+'px'">
</my-comp-2>

或者你可以在我的組件中創建任何 function 返回你想要什么並調用這個 function

注意:我使用 style.max-width,我不知道你的 my-comp2 是否有輸入

Angular 編譯器 package 中的DirectiveBinder class似乎將任何未命名模板引用視為對組件(如果它是一個)或元素(如果不是)的引用。

相關代碼在這里:

  node.references.forEach(ref => {
    let dirTarget: DirectiveT|null = null;

    // If the reference expression is empty, then it matches the "primary" directive on the node
    // (if there is one). Otherwise it matches the host node itself (either an element or
    // <ng-template> node).
    if (ref.value.trim() === '') {
      // This could be a reference to a component if there is one.
      dirTarget = directives.find(dir => dir.isComponent) || null;
    } else {
      // This should be a reference to a directive exported via exportAs.
      dirTarget =
          directives.find(
              dir => dir.exportAs !== null && dir.exportAs.some(value => value === ref.value)) ||
          null;
      // Check if a matching directive was found.
      if (dirTarget === null) {
        // No matching directive was found - this reference points to an unknown target. Leave it
        // unmapped.
        return;
      }
    }

    if (dirTarget !== null) {
      // This reference points to a directive.
      this.references.set(ref, {directive: dirTarget, node});
    } else {
      // This reference points to the node itself.
      this.references.set(ref, node);
    }
  });

第一個 if 分支是在沒有給出名稱時(即#ref#ref="" ),else 循環遍歷被檢查元素上的任何指令。 上面這表明沒有指令是可能的,這表明沒有在某些地方添加特殊的內置“元素”指令。

結論1:如果它是一個組件並且模板引用變量中沒有名稱,那么它總是引用該組件。

結論 2:在每種情況下都沒有特殊的內置指令。 某些標准 HTML 元素(例如<input> )可能存在例外情況,但這對我們沒有幫助。

暫無
暫無

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

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