@HostListener('change')不起作用 - Angular2 RC1

问题描述:

我已经创建了一个属性指令myOptional,意在用于表单中的输入,其目的是指示某些字段是可选的。这是通过向输入添加一个类来完成的,然后使用css伪元素::after显示可选文本。@HostListener('change')不起作用 - Angular2 RC1

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

所以,当该指令被初始化,我们的类添加到输入

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); 
} 

希望我说清楚了。任何帮助将不胜感激。

我最终通过了控件的值作为输入来解决这一点。 然后,在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(); 
     } 
    } 
} 

你是对的,'改变'是行不通的。真的不能说whay,却发现这在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 {} 
+0

感谢您的及时响应。但是,这不起作用。填充输入的值不会触发inputChanged方法 – Gonzalo

+0

我不想触发任何事件..请参阅我更新的答案并附加注释。或者,也许我没有得到你真正的问题.. – mxii

+0

通过更新窗体控件以编程方式设置输入的值。 '( this.form.controls [c])。updateValue(obj [c])'。当发生这种情况时,我希望可选课程被移除。但是,这不会触发您发布的inputChanged方法,也不会触发上面列出的onchange。 – Gonzalo