我有一个Angular 2应用程序。在我的注册页面上,我有一个帐单和送货地址。加载(ngOninit)时,将隐藏运输表格,仅在按下复选框并从帐单复制(setValue)值时,才会显示运输地址。这表明我们的客户想要其他地址。
因此,从此处打开/显示收货地址,并且未选中复选框。现在对我来说很奇怪的是,当用户输入无效时,假设一封电子邮件并尝试提交,它将刷新表格并复制帐单中的值,客户现在将再次输入送货地址。
这是片段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片段:
<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
的形式为Abstract Control,但实际上并没有按下或单击复选框。真的很奇怪。
偶然地,表单被“刷新”而不是页面。
答案 0 :(得分:0)
大家好,在这里我做了什么。观察后,我才意识到该复选框在技术上不属于表格的一部分。它只是一个隐藏和显示的切换按钮,这就是为什么在提交之前进行清理的原因,我们正在删除checkbillingvalue
属性,就是我的意思。
将输入更改为此。
<input
type="checkbox"
id="test-checkbox"
class="p-0 mr-3"
[checked]="checkBoxValue"
(change)="onCheckBoxEvent($event)"
/>
,并且在onCheckBoxEven
方法内部执行了相同的逻辑。这是我以前工作的重构。我认为与表单相关联的每个input
或标签都需要添加formcontrol。