未使用 Angular 2 指令在元素上设置高度

Chr*_*odz 4 angular2-directives angular

我正在尝试创建一个流体文本区域,但在使用“角度 2 方式”进行 DOM 操作时,无法在元素上设置高度。

成分:

import {Directive, ElementRef, HostBinding, HostListener} from '@angular/core';

@Directive({
  selector: '[fluidHeight]',
  host: {
    '(input)': 'setHeight()'
  }
})

export class FluidHeightDirective {

  constructor(private _elementRef: ElementRef) {}

  @HostBinding('style.height.px')
  height: number;

  setHeight() {
    this.height = this._elementRef.nativeElement.scrollHeight + 'px';
  }
}
Run Code Online (Sandbox Code Playgroud)

标记:

<textarea [(ngModel)]="model" fluidHeight></textarea>
Run Code Online (Sandbox Code Playgroud)

为什么我在setHeight函数中得到了正确的值,但高度没有在 上设置textarea

Gün*_*uer 8

如果您使用.px

@HostBinding('style.height.px')
Run Code Online (Sandbox Code Playgroud)

你也不应该这里添加它

this.height = this._elementRef.nativeElement.scrollHeight + 'px';
Run Code Online (Sandbox Code Playgroud)

使用任一

@HostBinding('style.height')
Run Code Online (Sandbox Code Playgroud)

或者

    this.height = this._elementRef.nativeElement.scrollHeight;
Run Code Online (Sandbox Code Playgroud)