【发布时间】:2020-01-31 19:34:06
【问题描述】:
我有一个 Angular 2 应用程序。在我的注册页面上,我有一个帐单和送货地址。在加载 (ngOninit) 时,运输表格被隐藏,运输地址仅在按下复选框并从帐单中复制 (setValue) 值时显示。这表明我们的客户想要一个不同的地址。
因此,从此处打开/显示送货地址并且未选中复选框。现在对我来说奇怪的是,当用户输入无效时,比如说一封电子邮件并尝试提交,它会刷新表单并复制账单中的值,客户现在将再次重新输入送货地址。
这里是 sn-p ts 文件:
ngOnInit() {
this.checkBoxDynamicValidator();
}
onSubmit(event: Event) {
event.preventDefault();
}
/**
* this function sets up the validation for the shipping address
* validation is controlled by the checkbox
*/
private checkBoxDynamicValidator(): void {
const changesCheckBox$ = this.companySignUpForm.get('checkBoxBilling')
.valueChanges;
const shipAddressAttrCtrl = this.companySignUpForm.get(
'ship_address_attributes'
) as FormGroup;
changesCheckBox$.subscribe((valOfCheckBox) => {
this.populateShippingAddress(valOfCheckBox);
if (valOfCheckBox) {
this.clearCustomValidators(shipAddressAttrCtrl);
} else {
this.setCustomValidators(shipAddressAttrCtrl);
}
});
}
/**
* populate shipping address if checkbox "same as billing" is unchecked
*/
private populateShippingAddress(isChecked: boolean): void {
const shipAddGroup = this.companySignUpForm.get('ship_address_attributes');
const billAddGroup = this.companySignUpForm.get('bill_address_attributes');
// TODO: move to a helpers
const selectedCountry = this.countries.find( country => Number(country.id) === Number(billAddGroup.value.country_id));
this.setShippingState(selectedCountry.states);
if (!isChecked) {
shipAddGroup.setValue({
firstname: billAddGroup.value.firstname,
lastname: billAddGroup.value.lastname,
address1: billAddGroup.value.address1,
address2: billAddGroup.value.address2,
city: billAddGroup.value.city,
zipcode: billAddGroup.value.zipcode,
phone: billAddGroup.value.phone,
country_id: billAddGroup.value.country_id,
state_id: billAddGroup.value.state_id
});
}
}
changesCheckBox$.subscribe((valOfCheckBox) => {} 每次页面出现错误或提交无效表单时都会触发此代码,即使未按下或更改复选框也是如此。我可以在这里防止默认吗?我做了一个阻止默认 onSubmit 的操作。
html sn-p:
<form novalidate [formGroup]="companySignUpForm">
... html here
<button[disabled]="companySignUpForm.pristine ||companySignUpForm.invalid ||companySignUpForm.get('billingType').value !== 'creditCard'"
(click)="onSubmit($event)">
{{ 'register' | translate }}
</button>
</form>
有什么想法吗?我觉得这是一个错误或什么的。我不确定,但这是一种奇怪的行为。我知道valueChanges 形成了抽象控件,但我实际上并没有按下或单击复选框。真的很奇怪。
顺便说一句,“刷新”的是表单而不是页面。
【问题讨论】:
-
我使用绑定到复选框的 ngModel 的属性(getter 和 setter)来控制表单控件之外的场景。在 setter 函数上调用 form.control.setValue 和 populeShippingAddress。
-
@LeonardoNeninger 你好,伙计。我想也做了同样的事情。我会发布答案。
标签: angular angular-reactive-forms