【问题标题】:Angular 2 detect changes to a readonly input's [ngModel] binding in directiveAngular 2 检测指令中只读输入的 [ngModel] 绑定的更改
【发布时间】:2017-02-20 11:32:55
【问题描述】:

我有这个指令,它根据文本区域的内容设置流体高度:

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

export class FluidHeightDirective implements AfterViewInit {

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit() {
    this.setHeight();
  }

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

  setHeight() {
    console.log(true)
    this.height = this.elementRef.nativeElement.scrollHeight;
  }
}

但是,当我使用 [ngModel]readonly 时,我无法让它工作:

<textarea [ngModel]="foo" fluidHeight readonly></textarea>

还有一个文本区域可以改变readonly 输入的内容。

我尝试过使用ngModelChangechangeinput,但它们似乎都不起作用。

有人知道怎么做吗?

【问题讨论】:

  • foo你的内容吗?
  • @Dinistro 是的。

标签: angular typescript angular2-directives


【解决方案1】:

二传手应该可以解决问题:

export class FluidHeightDirective implements AfterViewInit {

    @Input('fluidHeight')
    set content(content:any) {
        this.setHeight();
    }

    constructor(private elementRef: ElementRef) {}

    ngAfterViewInit() {
        this.setHeight();
    }

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

    setHeight() {
        console.log(true);
        this.height = this.elementRef.nativeElement.scrollHeight;
    }
}

【讨论】:

  • 我最终得到了一个接受 ngModel 的 Input,这与这个基本上是相同的解决方案。您不需要设置器来使其实际工作。
  • @Chrillewoodz 不错 :)
猜你喜欢
  • 2016-10-02
  • 2018-07-24
  • 2017-06-27
  • 2017-01-02
  • 1970-01-01
  • 1970-01-01
  • 2017-08-16
  • 2017-06-03
  • 2017-03-11
相关资源
最近更新 更多