Angular:为什么值更改(使用renderer2)不会触发事件绑定到该值

问题描述 投票:0回答:1

场景:检查this stackblitz

  • 当我通过键入内容更改输入值时,(keyup),(更改)和(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");
    }

}
angular events renderer elementref
1个回答
0
投票

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

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();        
    }
© www.soinside.com 2019 - 2024. All rights reserved.