>我有以下表单组:
this.order = new FormGroup({
City: new FormControl('', Validators.required),
Street: new FormControl('', Validators.required),
DateOfDelivery: new FormControl('', Validators.required),
CreditCard: new FormControl('', [Validators.required,/*Validators.pattern('^(?:4[0-9]{12}(?:[0-9]{3})?|[25][1-7][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35d{3})d{11})$')*/])
})
和以下组件.html
<form [formGroup]="order">
<label>City</label>
<br>
<input class="form-control" list="City" name="City" formControlName="City" placeholder="Choose City" (dblclick)='dblClickCity($event.target)'>
<datalist id="City">
<option value="New York">
<option value="Berlin">
<option value="London">
</datalist>
<br>
<label>Street</label>
<br>
<input type="text" class="form-control" placeholder="Please Input Street for Delivery"
formControlName="Street" (dblclick)='dblClickStreet($event.target)'>
<br>
<label>Shipping Date</label>
<br>
<input type="date" class="form-control" placeholder="First Name here" formControlName="DateOfDelivery">
<br>
<label>Credit Card:</label>
<br>
<input type="text" class="form-control" placeholder="Credit Card here" formControlName="CreditCard">
<br>
</form>
双击城市或街道窗体控件时,将调用以下函数,并使用用户的数据自动填充输入:
dblClickCity(target) {
console.log(target.touched);
target.value = this.city;
}
dblClickStreet(target) {
target.value = this.street;
}
但是,页面底部的确认按钮状态保持禁用状态([disabled]='!order.valid'(,并且仅在我手动按每个字段上的键后进行验证。
知道如何解决这个问题吗?
提前谢谢。
想通了。 必须手动使用 .setValue 方法并将其输入到双击处理程序中,如下所示:
dblClickCity() {
this.order.controls.City.setValue(this.city);
}
dblClickStreet() {
this.order.controls.Street.setValue(this.street);
}
为了将来参考,如果你想在不创建特定函数的情况下动态设置值,你可以执行以下操作:
dblClickHandler(event) {
const control = event.target.getAttribute('formControlName');
this.order.get(control).setValue(event.target.value);
}