Angular 2 change event on every keypress

后端 未结 11 1378
说谎
说谎 2020-11-27 09:36

The change event is only called after the focus of the input has changed. How can I make it so that the event fires on every keypress?



        
相关标签:
11条回答
  • 2020-11-27 09:54

    The secret event that keeps angular ngModel synchronous is the event call input. Hence the best answer to your question should be:

    <input type="text" [(ngModel)]="mymodel" (input)="valuechange($event)" />
    {{mymodel}}
    
    0 讨论(0)
  • 2020-11-27 09:58
    <input type="text" (keypress)="myMethod(myInput.value)" #myInput />
    

    archive .ts

    myMethod(value:string){
    ...
    ...
    }
    
    0 讨论(0)
  • 2020-11-27 10:01

    For Reactive Forms, you can subscribe to the changes made to all fields or just a particular field.

    Get all changes of a FormGroup:

    this.orderForm.valueChanges.subscribe(value => {
        console.dir(value);
    });
    

    Get the change of a specific field:

    this.orderForm.get('orderPriority').valueChanges.subscribe(value => {
        console.log(value);
      });
    
    0 讨论(0)
  • 2020-11-27 10:02

    I've been using keyup on a number field, but today I noticed in chrome the input has up/down buttons to increase/decrease the value which aren't recognized by keyup.

    My solution is to use keyup and change together:

    (keyup)="unitsChanged[i] = true" (change)="unitsChanged[i] = true"
    

    Initial tests indicate this works fine, will post back if any bugs found after further testing.

    0 讨论(0)
  • 2020-11-27 10:10

    In my case, the solution is:

    [ngModel]="X?.Y" (ngModelChange)="X.Y=$event"
    
    0 讨论(0)
  • 2020-11-27 10:11
    <input type="text" [ngModel]="mymodel" (keypress)="mymodel=$event.target.value"/>
    {{mymodel}}
    
    0 讨论(0)
提交回复
热议问题