@HostListener('更改')无效 - Angular2 RC1

时间:2016-09-20 23:22:34

标签: angular angular2-directives

我创建了一个属性指令myOptional,用于表单中的输入,其目的是指示某些字段是可选的。这是通过向输入添加一个类来完成的,然后使用css伪元素::after显示可选文本。

“可选”标签仅在输入值为空时显示,并且焦点位于其他位置。

因此,当指令初始化时,我们将类添加到输入

ngOnInit() {
    this.addOptionalClass();
}

在焦点上,我们删除了类,因此删除了可选标签

@HostListener('focus') onfocus() {
    this.removeOptionalClass();
}

在模糊时,如果输入值仍为空,我们会显示标签

@HostListener('blur') onblur() {
    if (this.isInputElement()) {
        let inputValue = (<HTMLInputElement>this.el).value;
        if (inputValue === '') this.addOptionalClass();
    }
}

到目前为止,这么好。通过更新窗体中的控件设置输入的值时会发生此问题。在这种情况下,当输入的值更新而不是空时,我想删除该类。

我假设我能够将事件监听器附加到onchange事件,但下面的代码根本没有被触发。我甚至尝试使用document.getElementBydId修改输入值,但没有成功。

@HostListener('change') onchange() {
    console.log((<HTMLInputElement>this.el).value);
}
希望我明白自己。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:2)

你是对的,&#39;改变&#39;不管用。不能说真的,但是在Github回购中找到了这个:https://github.com/angular/angular/issues/4593

请参阅此plunker如何使用keyup https://plnkr.co/edit/kIHogCxQaPPRQyqDVqTE?p=preview

进行操作
import {Component, NgModule, HostListener, Directive} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Directive({
  selector: 'input[myOptional]'
})
export class OptionalDirective {

  // THIS WILL BE FIRED IF SOMEONE CHANGES THE INPUT
  @HostListener('keyup', ['$event'])
  inputChanged(event) {
    if (event.target.value) {
      console.log('not empty!');
      // REMOVE YOUR CLASS HERE
    }
    else // ADD YOUR CLASS HERE
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
      <input myOptional />
    </div>
  `,
})
export class App {
  constructor() {
    this.name = 'Angular2'
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App, OptionalDirective ],
  bootstrap: [ App ]
})
export class AppModule {}

答案 1 :(得分:1)

我终于通过将控件的值作为输入传递来解决这个问题。 然后,在ngOnChanges生命周期钩子上,我评估输入并根据它是否有值来添加/删除类。

export class OptionalDirective implements OnInit, OnChanges {
    @Input('myOptional') private controlValue: string;

    constructor(private elementRef: ElementRef) {
        this.el = elementRef.nativeElement;
    }

    ngOnChanges(changes: { [propName: string]: SimpleChange }) {
        if (changes['controlValue'] &&
            !changes['controlValue'].isFirstChange()
            && changes['controlValue'].currentValue !== changes['controlValue'].previousValue) {
            if (this.controlValue) this.removeOptionalClass();
            else this.addOptionalClass();
        }
    }
}

答案 2 :(得分:0)

要检测 mongodb://host.docker.internal:37017 中输入值的变化,请使用 Directive

ngModelChange
相关问题