Angular2:获取event.target.value

时间:2017-11-07 08:09:55

标签: angular typescript

我希望通过以下代码获得event.target.value

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

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

但是console.log(val)的答案是什么......没有任何想法实际进行数据绑定?

4 个答案:

答案 0 :(得分:2)

我认为你应该使用(keyup)或其他键盘事件处理程序,如果你想使用(keyup)=“changeInput($ event)”来获取这个值,那么你可以访问你的DOM事件和值;)

答案 1 :(得分:1)

(input)="detail.changeOwner($event.target.value)"

ngModel (ngModelChange)="detail.changOwner($event)"

您还可以在表单控件(valueChanges)上订阅detail.ownerTx 另请参阅qsort()

答案 2 :(得分:1)

将输入行更改为此

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

并对此起作用:

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

答案 3 :(得分:0)

使用组件方法来实现转换,不能在模板中转换!

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

另见https://github.com/angular/angular/issues/35293