Angular is returning the message "Property does not exist error"

At the start of my component class, I initialize a number type like so:

import { .....


@Component({
   ....
})
export class JhiLoginModalComponent implements  OnInit {
   
    a: number;
 

   
    ngOnInit() {
      this.method();

    }
    method() {
     a=3;
    }

In my testing class:

import {...

  describe('LoginComponent', () => {
  
    let comp: ComponentClass;
        let fixture: ComponentFixture<ComponentClass>;
          beforeEach(async(() => {
            TestBed.configureTestingModule({
              ............
        }));
        
          beforeEach(() => {
            fixture = TestBed.createComponent(ComponnetClass);
            comp = fixture.componentInstance;
            ....
              });
              
                it ('Should display a value', async(() => {
fixture.detectChanges();
            console.log('lalalalla' + comp.method.a); //It prints lalalaundefined
            
        }));

When I print domElement, it shows undefined and displays the error message: Property a is undefined for type any

Did I make an injection mistake?? How can I access the component elements differently? If I try to use this number later on, it signifies that it is undefined.

Answer №1

ngOnInit is triggered by the Angular engine once the component is fully initialized and ready for use, which includes setting input properties. If you add a console.log to ngOnInit, you will notice that it is called after your test's console.log. Make sure to invoke fixture.detectChanges() first.

UPDATED (per your feedback):

I just realized that you are trying to log comp.method.a, but comp.method is actually a function and does not have an a property. You should be logging comp.a instead:

console.log('lalala' + comp.a);

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

Is it possible to limit the items in a TypeScript array to only accept shared IDs with items in another array?

I'm creating an object called ColumnAndColumnSettings with an index signature. The goal is to limit the values of columnSettings so that they only allow objects with IDs that are found in columns. type Column = { colId: string, width?: number, s ...

Is it possible to store any array of strings in localStorage?

I'm trying to save a list of addresses in local storage, like this: addresses["1 doe st, england","2 doe st, england", "3 doe st, england"] Each time I click on an address, I want it to be added to the array in local storage. However, my current imp ...

What is the reason behind VSCode importing packages from the TypeScript cache?

Recently, I initiated a react-native project using the CLI. Everything seems to be functioning properly, but I have noticed that the import is directing to the TypeScript cache instead of the local node_modules. Interestingly, I am not even utilizing TypeS ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Efficiently Measuring the Visibility Area of DetailsList in Fluent UI

I am currently utilizing the DetalisList component alongside the ScrollablePane to ensure that the header remains fixed while allowing the rows to scroll. However, I have encountered a challenge as I need to manually specify the height of the scrollable co ...

Every time I attempt to make an HTTP request, I encounter a cross-origin error

When I make requests from the browser, they are valid. However, when using the Angular 9 app, I receive a 401 error. Below is the header from Chrome: Request URL: http://localhost:1234/api/Common/GetMy_List Request Method: GET Status Code: 401 Referre ...

What is the result of using `X ? A : B` in typescript?

type TestAny = any extends 'a' ? 1 : 2 // => 1 | 2 why??? how to interpret? type TestUnknown = unknown extends 'a' ? 1 : 2 // => 2 type TestStringA = 'a' extends 'a' ? 1 : 2 // => 1 type SomeUnion = ' ...

Include an additional component in the array that is already in place

The provided data currently consists of an array with three elements. (3) [{…}, {…}, {…}] 0: {Capacity: "150", Series: "20", Make: "150", Model: "150", TowerHeight: "151", …} 1: {Capacity: ...

Is it possible to specify broad keys of a defined object in TypeScript using TypeScript's typing system?

const obj: {[key: string]: string} = {foo: 'x', bar: 'y'}; type ObjType = keyof typeof obj; Is there a way to restrict ObjType to only accept values "foo" or "bar" without changing the type of obj? ...

Typescript and Visual Studio Code Issue: Module "myimage.png" Not Found

I am encountering an issue where VS Code is complaining about not being able to find a module when trying to import an image from an assets directory within my project. Despite the fact that the image import works fine, I keep receiving the error message: ...

Manipulating information from one format to another

I am currently tackling the task of calculating scores based on departments within groups. For simplicity, I will focus on just one group as an example. Here is the data structure that I have: const data = [{ "id": "cklt7ln1k0922o0sabjkk74m9", ...

"Using rxjs, a value is delivered within the subscribe function

function createSingleMapService(mapServiceFactory) { return mapServiceFactory.switchSingleMapService().subscribe((service)=>{ return service }) } This snippet is a factory function in Angular that creates a single map service. The 's ...

Why is it that I am able to invoke my Redux action creators from the componentWillMount() method, but not from my event handler function?

I'm currently developing an application using React, Redux, and TypeScript. My Redux store is all set up with initial state and it's working fine in populating my components. Now, I am in the process of connecting a form that will trigger my act ...

Having difficulty retrieving form controls using array notation function

import { Component, OnInit } from '@angular/core'; import { GetTransactionService } from '../../../service/getTransaction/get-transaction.service'; import { Router, Routes, RouterModule } from '@angular/router'; import { FormB ...

Not all generic types specified with an extends clause are appropriately narrowed down as expected

Consider the following scenario: type MyType = 'val1' | 'val2' | 'val3'; const variable = 'val1' as MyType; const val2 = 'val2'; const val3 = 'val3'; declare function test<U extends MyType&g ...

What is the best way to postpone resolving a dependency within the injector?

I want to dynamically configure the injector when ngOnInit is triggered. Here's my approach: <my-component [config]="someConfig"></my-component> // my.component.ts import { CONFIG_TOKEN } from 'injector_tokens'; @Co ...

Optimizing data aggregation from various components into a single source in Angular 6

As a newcomer to Angular, I have a question regarding my use of a Stepper component from Angular Material. Each step within the Stepper contains different components where customer data is collected using multiple input fields. Below is an example of the ...

What can be done to prevent the angular material select from overflowing the screen?

I have integrated an Angular Material Select component into my application, which can be found here: https://material.angular.io/components/select/overview. The issue I am facing is that when the select element is positioned near the bottom of the screen a ...

Ways to handle route initialization in Angular 13 when starting the app?

What is the most effective way to handle route resolution before components are loaded? I want to avoid using guards for every single route, and I need to load a component on the '/' path. Using a parent '/' path without a component but ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...