Angular 8 @viewChild directive resulting in a null value

stripeService.ts

  @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef;
  stripe = Stripe(environment.stripe.pubKey);

  async initStripeElements() {
    const elements = this.stripe.elements();
    const cardElement = elements.create('card');
    cardElement.mount(this.cardElementForm.nativeElement);
  }

Note: I have included additional code. This is the service file that I am importing into my page component.

page.component.html

 <form #saveCard="ngForm" class="saveCardForm">
              <ion-item>
                <div id="cardElementForm" #cardElementForm></div>
                <ion-text *ngIf="error">{{ error }}</ion-text>
              </ion-item>
              <ion-item>
                <ion-text (click)="this.payments.initStripeElements()">Initialize form</ion-text>
              </ion-item>
              <ion-item>
                <ion-text (click)="this.payments.saveCard()">Submit data</ion-text>
              </ion-item>
            </form>

page.component.ts

import { PaymentService } from '../services/stripeService.ts';

I am encountering an error:

TypeError: this.cardElementForm is undefined

Can anyone help me identify where the issue lies? I seem to be stuck at this point.

Answer №1

To optimize your service, it is recommended to remove

@ViewChild('cardElementForm', { static: false })
as your service does not have access to the template reference #cardElementForm. Instead, a better approach would be:


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  @ViewChild('cardElementForm', { static: false }) cardElementForm: ElementRef;

  constructor(private payService: PayService) {}

  ngAfterViewInit() {
     this.payService.cardElementForm = this.cardElementForm;
  }
}

Make sure to include the attribute cardElementForm: ElementRef; in your service.

Answer №2

Ensure that you are invoking the function createStripeForm() within the ngAfterViewInit lifecycle hook.

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

TypeScript requires that when explicitly specifying the return type of a generator, the `Generator.prototype.return` function must accept

I am utilizing a generator function to serve as a consumer for accumulating strings: function *concatStrings(): Generator<void, string, string> { let result = ''; try { while (true) { const data = yield; result += data; ...

Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object: { id: 14070 project: {id: 87, name: "Test project for time tracking"} issue: {id: 10940} user: {id ...

Guide to implementing a Page Object Model for improved debugging of Protractor tests

Introduction I am on a mission to streamline my e2e testing code using the Page Object Model for easier maintenance and debugging. My Approach When embarking on creating end-to-end tests with Protractor, I follow these steps to implement the Page Object ...

"Augury Angular 2 is like a tree that generates insights like no

As I work on documenting my project, I am looking to create documentation that will make it easier for beginners to understand the project's structure in the future. I am using Angular2 and documenting with Typedocs. My question is: Are there any solu ...

The error message "Unable to access 'useContext' property of null" appeared

I am currently in the process of developing a component library using Material UI, TypeScript, and Rollup. The package has been successfully published, but I am encountering an error when trying to import it into a new project: "Uncaught TypeError: C ...

having difficulty configuring drizzle on express

When configuring the database connection with MySQL using drizzle, I encountered a puzzling situation. I am utilizing express and top-level await without async, but I'm unsure of how it all fits together. import { drizzle } from "drizzle-orm/mysq ...

Unveiling individual modules of an Angular library using public-api.ts in the latest version of Angular (Angular 13)

After completing an upgrade on my Angular library project from version 11 to 13, I encountered an issue when attempting to execute the ng build command. In version 11, the setup looked like this: I had multiple smaller modules, each containing various co ...

Error message: "Error encountered while building Next.js - ReferenceError: 'describe' is not defined"

I am facing difficulties achieving a successful next build without encountering the following error: > Build error occurred { ReferenceError: describe is not defined Although the dev server and tests execute smoothly, it appears that the jest global d ...

Is there a way to execute Angular code synchronously similar to how it is done in C#?

Trying to replicate a C# application in Angular is proving to be challenging for me, particularly when it comes to ensuring that the code runs synchronously. Consider the following example: private void doChecks() { if (isInvoiced()) return; ...

The object literal can only define properties that are already known, and 'data' is not found in the type 'PromiseLike<T>'

When making a request to a server with my method, the data returned can vary in shape based on the URL. Previously, I would cast the expected interface into the returned object like this: const data = Promise.resolve(makeSignedRequest(requestParamete ...

The issue encountered during the construction of the nrwl library project is that object Object is not recognized as a PostCSS

We are currently facing an issue with our nrwl-nx workspace library project (based on Angular 8) that contains 3-4 angular libraries. While the ng serve function works properly, we have started encountering errors when trying to run ng build my-lib. On ou ...

Include asterisk symbol at the end of a web address following a designated keyword

I currently have a URL structured in the following way: https://localhost:8080/user/login But, there is an option to manually add query parameters which could result in a URL like this. https://localhost:8080/user/login?ten=123456 This leads me to seek ...

Differentiating between model types and parameters in Prisma can greatly enhance your understanding of

Consider the following scenario: const modifyData = async(data, settings) => { await data.update(settings) } In this case, the data refers to any data source, and the settings consist of objects like where and options for updating the data. How can ...

Tips for utilizing a function to assess ngClass conditional statement in Angular 2

So as I loop through my list using *ngFor, the code snippet is like this: [ngClass]="{'first':isStartDate(event,day)}" The function isStartDate is defined in my component. An error message appeared: "Unexpected token : " ...

Encountering CORS Error: Challenge in sending post requests with NodeJs and Angular

Whenever I attempt to make a post request, I encounter the following error message: Access to XMLHttpRequest at 'http://localhost:3002/api/products/checkout' from origin 'http://localhost:4200' has been blocked by CORS policy: Request ...

What are the steps for transitioning an Angular application from MonoRepo to PolyRepo?

Having created three separate Angular applications with individual workspaces, projects, and repositories, I am able to share modules among them using @angular-architects/module-federation. However, I am facing challenges when it comes to sharing component ...

Troubleshooting Issue: Angular 6 - Authentication token interceptor not including headers

After experimenting with various approaches using Angular 6 for the past couple of days, I recently tried implementing a solution mentioned in this post: . Despite my efforts, the header in the requests still remains unset. import {Inject, Injectable} fro ...

Can the child component ensure that the Context value is not null?

In the process of developing a Next.js/React application with TypeScript, I've implemented a UserContext in pages/_app.js that supplies a user: User | null object to all child components. Additionally, there's a ProtectedRoute component designed ...

Enrolling a new plugin into a software repository

I have 5 unique classes: ConfigManager ForestGenerator TreeCreator NodeModifier CustomPlugin My goal is to create an npm module using TypeScript that incorporates these classes. The main feature I want to implement is within the ConfigManager clas ...

Trigger a (click) event on the MatTab in Material design

I have a dynamic loop through tabs and I want to be able to trigger a (click) event in order to load different options when a tab is selected. Is it not possible to use a simple click event on dynamically created tabs? I tried using (selectChange) on the ...