The data type 'AbstractControl | null' cannot be assigned to type 'FormGroup'

I am facing an issue with passing the [formGroup] to child components in Angular. The error message says

Type 'AbstractControl | null' is not assignable to type 'FormGroup'
. I have double-checked my conditions and initialization, but I can't figure out why this error persists. The problematic code snippet is
[formGroup]="linkAccounts?.get('bank')"
in link-accounts.component.html

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);
}

Answer №1

You need to ensure that the linkAccounts?.get('bank') is casted to a FormGroup in order to be assigned to the formGroup. This is necessary because the type of the form's controls is AbstractControl | null.

#1 Solution: Create a getter with the type 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 Solution: Use a $any() casting in the component template:

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to eliminate duplicate objects from an array using Angular 6

I'm having trouble removing duplicate value objects in an array and it's not working as expected. I believe the duplicate function is functioning correctly, but the changes are not being reflected in the li list. Can you pinpoint where I need to ...

Understanding the behavior of the enter key in Angular and Material forms

When creating forms in my MEAN application, I include the following code: <form novalidate [formGroup]="thesisForm" enctype="multipart/form-data" (keydown.enter)="$event.preventDefault()" (keydown.shift.enter)="$ev ...

Troubleshooting: Angular 2 router events subscription not triggering

Currently, I am utilizing a breadcrumbs component that subscribes to the router events. However, there is an issue where the subscription does not trigger the first time the component loads. ngOnInit(): void { console.log("oninit beradcumbs"); this.ro ...

Enhancing ag-grid's agRichSelectCellEditor with an arrow for a more user-friendly drop-down experience

The agRichSelectCellEditor currently lacks a visual indicator that it is a drop-down menu. To enhance user understanding, I am interested in including a downward arrow within the cell display. Despite looking through the documentation extensively, I have ...

Accessing an Array from a service method in Angular and passing it to my main component

Within my api-service.ts, I have an array that holds some data. public getData():Observable<any[]> { return Observable.toString[ObsResult]; } Now, in the main component, I am attempting to call the getData() method to render the data in ...

Bug in timezone calculation on Internet Explorer 11

I've spent hours researching the issue but haven't been able to find any effective workarounds or solutions. In our Angular 7+ application, we are using a timezone interceptor that is defined as follows: import { HttpInterceptor, HttpRequest, H ...

Guide to displaying the value of a field in an object upon clicking the inline edit button using TypeScript

Is it possible to console log a specific attribute of an object when clicking on the edit button using the code below? Please provide guidance on how to utilize the index to access the value of "name". Refer to the last line in the code with the comment. ...

Automate the process of triggering the "Organize Imports" command on a VSCode / Typescript project through code

Is there a way to automatically run VSCode's 'Organize Imports' quickfix on every file in a project, similar to how tslint can be run programatically over the entire project? tslint --project tsconfig.json --config tslint.json --fix I want ...

Ways to import a library in JavaScript/TypeScript on a web browser?

I'm currently working on a project that involves a TypeScript file and an HTML page. Right now, I am loading the necessary libraries for the TypeScript file in the HTML Page using script tags like <script src="https://unpkg.com/<a href="/cd ...

What is the Angular2 version of angular.equals?

Currently, I am in process of upgrading an Angular 1 project to Angular 2. In the old project, I used angular.equals for comparing objects like this: angular.equals($ctrl.obj1, $ctrl.newObj);. I tried looking online for a similar method in Angular 2 but ...

Encountering an Unexpected Token in Angular 15, API 29 App

Upon attempting to build and run my Angular application on an Android 10 (API 29) emulator, I encounter a white screen on the device along with the following error message in Android Studio: E/Capacitor/Console: File: http://localhost/ - Line 610 - Msg: Sy ...

Disallow negative numbers but allow decimals in HTML input

I need help restricting user input to prevent negative numbers while still allowing floating point numbers in my Angular project. Any suggestions using Angular tools would be greatly appreciated. Thanks! ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

Having trouble with the "Vs Code nx console generate" command? It seems that there are no flags available to configure

My issue involves the nx console extension installed in my Visual Studio Code. Every time I attempt to use the generate command for components, services, or libraries, I receive an error message stating "ng generate @schematics/angular:component This com ...

Troubleshooting the issue with mocking the useTranslation function for i18n in JEST

Currently, I am facing an issue with my react component that utilizes translations from i18next. Despite trying to create tests for it using JEST, nothing seems to be getting translated. I attempted to mock the useTranslation function as shown below: cons ...

Retrieving Information from a JSON Object using Angular 2

I'm dealing with a JSON object response. The object looks like this: {auth_token: "60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45"} auth_token:"60a483bc0b1bc4dc0231ff0b90a67be1dad6ef45" proto : Object My goal is to extract the value "60a483bc0b1bc4dc0231f ...

Designing a versatile Angular component for inputting data (Mailing Address)

Currently, I am in the process of developing an Angular 11 application that requires input for three distinct mailing addresses. Initially, I thought I had a clear understanding of what needed to be done, only to encounter warnings about elements with non- ...

Problem with Angular app not loading in IE 11 due to ES6 targeting

I have encountered an issue while developing a new application with IE11 as the target browser. When I set the target to es6, the app fails to load and displays the error shown below. https://i.stack.imgur.com/FL8BG.png However, when I switch the target ...

Guide to accessing Angular app on a mobile device within the same network

I'm facing an issue with my Angular App when trying to access it on mobile within the same network. I've attempted running ng serve --host <my IP> or ng serve --host 0.0.0.0 and it works well. However, the problem arises because the applica ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...