Angular/JS在一个方法中获得两个$event.target.value



我正在尝试从->搜索邮政编码。我有两个输入字段和一个简单的方法。是否可以使用带有2个参数的方法?这是我的方法:

searchPostalCode(from:number, to:number):void{
console.log('from:' + from);
console.log('to:' + to);
}

我的输入:

<input type="text" class="form-control col-sm-1" placeholder="from" (input)=searchPostalCode($event.target.value)>
<input type="text" class="form-control col-sm-1" placeholder="to" (input)=searchPostalCode($event.target.value)>

我认为最简单的方法是在组件上有两个属性和两个更新这些属性的方法:

postalCodeFrom: number;
postalCodeTo: number;
updateFrom(value: number): void {
this.postalCodeFrom = value;
this.search();
}
updateTo(value: number): void {
this.postalCodeTo = value;
this.search();
}
search(): void {
// Make better checks - this will fail on 0
if (!this.postalCodeFrom || !this.postalCodeTo) {
// run some logic?
return;
}
// run the actual search.
}

然后将您的输入绑定到该方法:

<input type="text" class="form-control col-sm-1" placeholder="from" (input)=updateFrom($event.target.value)>
<input type="text" class="form-control col-sm-1" placeholder="to" (input)=updateTo($event.target.value)>

当然还有其他方法(比如使用RxJS(,但以上方法应该足够好。

也许您应该使用表单模块并执行这样的操作。

myForm: FormGroup;
from = '';
to = '';

内部ngOnInit:

this.myForm = this.formBuilder.group({
from: [this.from],
to: [this.to]
});
this.myForm.controls['from'].valueChanges.subscribe(value => {
console.log(value);
});
this.myForm.controls['to'].valueChanges.subscribe(value => {
console.log(value);
});

和HTML:

<form [formGroup]="myForm">
...
<input type="text" name="from" [(ngModel)]="from" formControlName="from" placeholder="from"/>

<input type="text" name="to" [(ngModel)]="to" formControlName="to" placeholder="to"/>
...
</form>

最新更新