網站搜尋

angular - 從指令獲取值以供將來使用


我正在嘗試將工具列固定在視窗底部,但當我向下滾動時,其他元件總是會蓋在它上面。我想到的解決方案是取得工具列的高度,然後將“其他元件”的下邊距/填充設為該值。這樣它就永遠不會蓋在工具列上。

取得高度指令.ts

import { Directive, ElementRef, OnInit } from '@angular/core';
import { EventEmitter } from '../../../../node_modules/protractor';

@Directive({
  selector: '[appGetHeight]'
})

export class GetHeightDirective implements OnInit{
  constructor(public el: ElementRef) {}

  ngOnInit() {
    let styles = getComputedStyle(this.el.nativeElement);
    console.log(styles.height);
  }

}

我將那個指令應用到這個上:

在哪裡申請指令.html

    <div appGetHeight class="col">
      <p >Lorem ipsum dolor sit amet consectetur adipisicing elit. Architecto ipsum repellat illum corporis, possimus consequatur qui nisi ipsa in. Molestiae, dolor. Fugit, eum quas. Provident neque id optio facilis velit.</p>
    </div>

透過這個,我可以在 console.log 中取得工具列的高度,顯示類似 66.8px 的內容。我現在想使用那個 '100px' 來設置兄弟組件中某個元素的 margin-bottom,但我找不到任何解決方案。

謝謝你的幫助。

答案#1

若要訪問指令的實例,可以考慮使用 exportAs 變數。您可以在此進一步閱讀:

https://netbasal.com/angular-2-take-advantage-of-the-exportas-property-81374ce24d26

摘要: 使用 export 時,您可以獲得訪問組件指令的可能性。要獲得這種訪問,您需要在 @Directive 裝飾器中添加 exportAs 並給它一個名稱。

要將指令儲存到父視圖的變數中,你可以使用以下語法:

這裡有一個使用你的程式碼的範例:

@Directive({
  selector: '[appGetHeight]',
  exportAs: 'heightDirective'
})
export class GetHeightDirectiveDirective implements OnInit {
  public styles: CSSStyleDeclaration;

  constructor(public el: ElementRef) {
  }

  ngOnInit() {
    this.styles = getComputedStyle(this.el.nativeElement);
    console.log(this.styles.height);
  }

}

注意:

  1. 我將 styles 改成 this.styles,否則變數會在 ngOnInit 之後被刪除,因為 let 是區塊作用域的變數。

  2. 看看第三行的 "exportAs"。

用法:

<div appGetHeight #varWithDirective="heightDirective">Test</div>

<div class="login-background" [style.margin-bottom]="varWithDirective.styles.height" >

請注意這裡的 #varWithDirective="heightDirective",heightDirective 必須代表 exportAs 的名稱。然後我就可以通過變數 #varWithDirective 訪問該指令的所有值。

我希望這對你有幫助。

重要: 你所要求的問題絕對可以用不同的方法解決。用 JavaScript 來解決 CSS 問題是不好的做法。但為此我需要更多資訊。

考慮使用:z-index/固定定位以及可能的 CSS 網格。

答案#2

  1. 簡單的 @Output 等等可以訂閱這個變化。

  2. 建立一個服務,例如 AppHeightService。在其中建立一個 Subject 組件變數,它會將計算出的高度發送給所有訂閱它的人。要從指令通知服務,只需在服務中建立一個函數,例如:emitHeight(height: string)。在此函數中,你可以使用此值呼叫 subject 的 next 方法。