类型 'AbstractControl | null' 不可分配给类型 'FormGroup'

Type 'AbstractControl | null' is not assignable to type 'FormGroup'

我在将 [formGroup] 传递给 Angular 中的子组件时遇到问题。它说 Type 'AbstractControl | null' is not assignable to type 'FormGroup'。我想我已经设置了所有安全条件并且我已经很好地初始化了它。我不明白为什么这仍然发生。错误在 link-accounts.component.html

中的 [formGroup]="linkAccounts?.get('bank')"

register.component.ts

linkAccountsForm = this.formBuilder.group({
  bank: this.formBuilder.group({
    bank_name: [null, Validators.required],
    account_name: [null, Validators.required],
    account_number: [null, Validators.required],
    swift_code: [null, Validators.required],
  }),
  credit_card: this.formBuilder.group({
    name: [null, Validators.required],
    card_number: [null, Validators.required],
    cvc: [null, Validators.required],
    exp_date: [null, Validators.required],
  }),
});

register.component.html

<form
  [formGroup]="linkAccountsForm"
  (ngSubmit)="onLinkAccount(linkAccountsForm)"
>
  <app-link-accounts
    [linkAccounts]="linkAccountsForm"
    [step]="step"
    [submitted]="submitted"
  ></app-link-accounts>
</form>

link-accounts.component.ts

 @Input() linkAccounts!: FormGroup;
 @Input() step!: number;
 @Input() submitted!: boolean;

link-accounts.component.html

<div [formGroup]="linkAccounts" *ngIf="step === 2">
  <app-bank
    [parentForm]="linkAccounts"
    [formGroup]="linkAccounts?.get('bank')"
  ></app-bank>
  <button type="submit" class="custom-login-button">Done</button>
</div>

bank.component.ts

public bank!: FormGroup;
@Input() parentForm!: FormGroup;

constructor(private controlContainer: ControlContainer) {}

public ngOnInit(): void {
  this.bank = this.controlContainer.control as FormGroup;

  console.log(this.logForms)
}

public logForms(): void {
  console.log('Hobbies form', this.bank);
  console.log('Parent (Hero) form', this.parentForm);
}

您必须将 linkAccounts?.get('bank') 转换为 FormGroup 才能分配给 formGroup,因为 controls 形式的 typeAbstractControl | null.

#1 解决方案: 使用 getter 和 FormGroup 类型:

get bankFormGroup(): FormGroup {
  return this.linkAccountsForm?.get('bank') as FormGroup;
}
<div [formGroup]="linkAccounts" *ngIf="step === 2">
  <app-bank [parentForm]="linkAccounts" [formGroup]="bankFormGroup"></app-bank>
  <button type="submit" class="custom-login-button">Done</button>
</div>

#2 解决方案: 在组件模板中使用 $any() 转换:

<div [formGroup]="linkAccounts" *ngIf="step === 2">
  <app-bank
    [parentForm]="linkAccounts"
    [formGroup]="$any(linkAccounts?.get('bank'))"
  ></app-bank>
  <button type="submit" class="custom-login-button">Done</button>
</div>