【发布时间】:2020-06-06 14:18:57
【问题描述】:
我有 2 个并行组件,我正在尝试将 1 个组件注入其他组件。以下是我的组件文件:
RegisterComponent.html
<mat-tab #tab label="Contact Details">
<ng-template matTabContent>
<app-contact-details></app-contact-details>
</ng-template>
</mat-tab>
<button type="button" (click)="changeTabOrStepViaContinue()" class="">Continue</button>
RegisterComponent.ts
changeTabOrStepViaContinue() {
if (this.tabGroup._tabs.first.isActive) {
this.tabGroup.selectedIndex += 1;
} else if (this.tabGroup._tabs.last.isActive /* && this.isContactFormValid() */) {
this.contactDetails.validateContactDetails(); //throws Error
console.log("Contact details form: ", this.contactDetailsForm);
} else if (this.isPersonalDetailsFormValid()) {
this.tabGroup.selectedIndex += 1;
}
}
ContactDetailsComponent.ts(被注入的组件)
ngOnInit() {
console.log("Contct det ngOnInit fired......")
this.contactDetailsForm = this.formBuilder.group({
primaryMobile: ['', [Validators.required]],
primaryMobileOwner: ['', [Validators.required]],
primaryEmail: ['', [Validators.required]],
primaryEmailOwner: ['', [Validators.required]],
landLine: [''],
country: ['', [Validators.required]],
pinCode: ['', [Validators.required]],
flat: ['', [Validators.required]],
street: [''],
postOffice: ['', [Validators.required]],
locality: ['', [Validators.required]],
district: ['', [Validators.required]],
state: ['', [Validators.required]]
})
}
validateContactDetails(): boolean {
console.log(this.contactDetailsForm);
Object.keys(this.contactDetailsForm.controls).forEach(elt => {
this.contactDetailsForm.get(elt).markAsTouched();
})
if (this.contactDetailsForm.valid) {
this.contactDetails.emit(this.contactDetailsForm);
return true;
}
return false;
}
我通过包含@Injectable({providedIn:'root'}) 使ContactDetailsComponent 成为服务,并将其注入RegisterComponent 的构造函数中作为constructor(private contactDetails:ContactDetailsComponent)。
当我选择特定的 mat-tab 时,ContactDetailsComponent 的 ngOnInit 被触发(它在 ng-template 内被延迟加载)但是在单击继续按钮时,它显示错误 TypeError: Cannot read property 'controls' of undefined。
为什么 FormGroup undefined 在本地函数中?
更新
我为ContactDetailsComponent 安慰了this 上下文,发现它没有contactDetailsForm 属性。然后我将变量声明从contactDetailsForm:FormGroup 更改为contactDetailsForm:FormGroup=new FormGroup({}),然后它在this 上注册,但在ngOnInit 内的FormControls 上的验证不再起作用。我还在组件中添加了另一个 FormGroup,并且发生了同样的事情。看起来this 只注册了已初始化的属性,但我不确定为什么会这样。
【问题讨论】:
标签: javascript angular typescript formgroups