1

场景: 检查这个 stackblitz

  • 当我通过键入内容更改输入值时,(keyup)、(change)和(ngModelChange)事件都会触发;
  • 当我通过 renderer2 更改输入值时,没有任何事件触发

我想要什么

我想以编程方式键入一些内容,以便该输入事件上的事件触发

相关代码

import { Component, OnInit, OnChanges, AfterViewInit ,ElementRef, Renderer2, ViewChild, ViewChildren } from '@angular/core';


@Component({
  selector: 'dom-comp',
  template: `

  <p><b>the Issue</b>: when i try to change the value of an input field by renderer2 - the (change) and (ngModelChange) events are not triggered, even though the values are changed !!</p>
  <input type='text' #myIn placeholder="if you type here, events will trigger"  [(ngModel)]='myInputVal' 
(change)="inputChanged()" 
(ngModelChange)="ngModelChanged()" 
 (keyup)="keyPressed($event)"
/> <br/>{{myInputVal}}

<br/>
<button #myBtn type="button" (click)='setFocusAndVal()'>press this button to change the value of the input field</button>

  `,
  styles: [ `input{width:90vw;}` ]
})
export class DomComponent implements OnInit, OnChanges, AfterViewInit {
  subTitle = 'Dom Component';
    @ViewChild('myIn')myInput:ElementRef;
    @ViewChild('myBtn')myButton:ElementRef;


    constructor(private elR:ElementRef, private rend:Renderer2){}

    ngOnInit(){}
    ngOnChanges(){}

    ngAfterViewInit(){
        console.log(this.myInput);
        //this.rend.setStyle(this.myInput.nativeElement, 'background', 'lightBlue');
        //this.rend.setStyle(this.myInput.nativeElement, 'color', 'red');
        this.myInput.nativeElement.focus();        
    }

    keyPressed(event){
        console.log("key pressed",event.target.value);

    }

    setFocusAndVal() {
        this.myInput.nativeElement.value = 'triggered by (button)';
        this.myInput.nativeElement.focus();
        setTimeout(()=>{ this.myInput.nativeElement.value = ' '; }, 1000);
        setTimeout(()=>{ this.myInput.nativeElement.value = ''; }, 3000);
        this.myButton.nativeElement.focus();
    }

    inputChanged() {
        console.log("inside inputChanged");
        this.rend.setProperty(this.myInput.nativeElement, 'value', 'triggered by (change)');
        this.myInput.nativeElement.focus();
        setTimeout(()=>{ this.rend.setProperty(this.myInput.nativeElement, 'value', ' '); }, 1000);
    }

    ngModelChanged(){
        console.log("inside ngModelChanged");
    }

}
4

1 回答 1

0

您可以尝试在 ngAfterViewInit 中添加 renderer2 的监听方法

ngAfterViewInit(){
        console.log(this.myInput);

        this.renderer.listen(this.myInput.nativeElement, 'keyup', () => {
             //Add your stuffs
        });

        //this.rend.setStyle(this.myInput.nativeElement, 'background', 'lightBlue');
        //this.rend.setStyle(this.myInput.nativeElement, 'color', 'red');
        this.myInput.nativeElement.focus();        
    }
于 2019-04-15T12:32:39.997 回答