Angular2:getting event.target.value

Viewed 54228

I want to get event.target.value by the codes below.

    <input 
      mdInput 
      #owner
      required 
      placeholder="荷主" 
      [formControl]="detail.ownerTx" 
      [mdAutocomplete]="autoTxt" 
      (change)="detail.changeOwner(owner.value)"
     >

   class Detail {
    changeOwner(val: string){
     console.log(val);
    }
   }

but the answer of the console.log(val) is nothing.... any idea to actually do the data-binding??

4 Answers

I think you should use (keyup) or another keyboard event handler if you want to get this value using (keyup)="changeInput($event)" then you can access you DOM event and value ;)

change the input line to this

<input 
      mdInput 
      #owner
      required 
      placeholder="荷主" 
      [formControl]="detail.ownerTx" 
      [mdAutocomplete]="autoTxt" 
      (change)="detail.changeOwner($event)">

and function to this :

class Detail {
    changeOwner($event){
     //You will get the target with bunch of other options as well.  
     console.log($event.target.value);
    }
   }

Use a component method to implement the cast, it is not possible to cast in templates!

@Component({
  selector: '...',
  template: '<input (keyup)="filter(target($event).value)">',
})
export class SomeCmp {
  target(event: KeyboardEvent): HTMLInputElement {
    if (!(event.target instanceof HTMLInputElement)) {
      throw new Error("wrong target");
    }
    return event.target;
  }
}

Also see https://github.com/angular/angular/issues/35293

Related