【问题标题】:Angular FormGroup is undefined inside a local methodAngular FormGroup 在本地方法中未定义
【发布时间】: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


    【解决方案1】:

    您是否尝试从父级调用子方法?

    据我所见,您不需要注入任何东西,除非它需要您没有告诉我们的其他地方。您只需将 id 添加到您的 app-contact-details 并使用 ViewChild 来获取参考。有多种使用 ViewChild 的方法,这可能不是最适合您的方法,但它只是一个示例。

    <app-contact-details #contactDetail></app-contact-details>
    
    @ViewChild('contactDetail') contactDetail: ContactDetailsComponent; // In the parent ts file
    

    然后,如果您想查看它是否已被初始化,请检查您应该可以访问子函数的父项的 ngAfterViewInit(您可能需要将 contactDetail 强制转换为您的组件类型,或者您需要进行不同的 ViewChild 初始化)如果它们是公开的,因为此时应该调用孩子的 OnInit。

      ngAfterViewInit() {
         // you can try to print your form
      } 
    

    您的表单未初始化的原因是您没有引用正确的实例,除非该组件是单例。使用内容投影(就像你正在做的那样)组件将在 Angular 开始显示它时被初始化(这是在子进程中调用 OnInit 的地方)。

    【讨论】:

    • 感谢您的回复。实际上,组件 dot 确实具有父子关系。它们是兄弟组件。 contactDetails 组件必须在至少 5 个不同的地方使用,这就是我将其作为服务的原因
    • 如果您使用内容投影注入它,则它不是兄弟。在 5 个不同的地方使用一个组件不需要服务,这就是使用组件的意义所在!
    • 我也尝试使用您给出的答案,但它会引发错误cannot read property 'validateContactDetails' of undefined
    • 你从哪里调用它的?
    • 来自RegisterComponent。 ts 文件
    猜你喜欢
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 2015-09-13
    • 1970-01-01
    相关资源
    最近更新 更多