What is the solution to the error message "Unable to assign property of undefined"?

I am currently working on an angular countdown timer and encountering a TypeError when attempting to access a variable from another component. I am struggling to identify the root cause of this issue. Here is the video tutorial that I am using as a reference: Countdown Timer. Below you can find my code:

Timer.component.ts

import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-timer',
  template: `<span>{{ currentValue }}</span>`,
  styleUrls: ['./timer.component.css'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class TimerComponent implements OnInit {

  @Input() startAt = 0;

  @Output() counter = new EventEmitter<string>();

  currentValue = '';
  constructor(private changeDetector: ChangeDetectorRef) { }

  ngOnInit(){
  }

  public start(){
    this.currentValue = this.formatValue(this.startAt);
    this.changeDetector .detectChanges();
  }

  private formatValue(v){
    const minutes = Math.floor(v/60);
    const formattedMinutes = (minutes > 9) ? minutes : ('0' + minutes);

    const seconds = v%60;
    const formattedSeconds = (seconds > 9) ? seconds : ('0' + seconds);

    return `${ formattedMinutes } : ${ formattedSeconds }`;
  }
}

questions.component.ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { TimerComponent } from '../timer/timer.component';

export class QuestionComponent implements OnInit {

  @ViewChild('counter', { read: TimerComponent })
  private counter: TimerComponent;

  ngOnInit() {
      this.counter.startAt = 2700;
      this.counter.start();
  }
}

question.component.html

<app-timer #counter></app-timer>

ERROR

core.js:6185 ERROR TypeError: Cannot set property 'startAt' of undefined
    at QuestionComponent.ngOnInit (question.component.ts:122)
    at callHook (core.js:4686)
    at callHooks (core.js:4650)
    at executeInitAndCheckHooks (core.js:4591)
    at refreshView (core.js:11814)
    at refreshDynamicEmbeddedViews (core.js:13154)
    at refreshView (core.js:11819)
    at refreshComponent (core.js:13229)
    at refreshChildComponents (core.js:11527)
    at refreshView (core.js:11848)

I would greatly appreciate any assistance in troubleshooting this issue with my code.

Answer №1

It is important to ensure that the child component is fully initialized before making any further actions using the AfterViewInit lifecycle hook.

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';

export class ExampleComponent implements OnInit, AfterViewInit {

    ngAfterViewInit() {
        this.timer.startAt = 5000;
        this.timer.start();
    }

}

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

Why isn't the parent (click) event triggered by the child element in Angular 4?

One of my challenges involves implementing a dropdown function that should be activated with a click on this specific div <div (click)="toggleDropdown($event)" data-id="userDropdown"> Username <i class="mdi mdi-chevron-down"></i> </d ...

Dealing with multiple validation error messages in Angular Material 2

Working on a form using Angular Material 2, I am implementing a template-driven approach with an email input that requires two validators: required and email. The documentation for the input component (available at https://material.angular.io/components/co ...

Exploring Page Navigation Techniques in Angular 2

Exploring the world of Angular 2, I've come across a task to implement pagination. In my research, it led me to realize that the pagination logic must be coded in systems.config.js. My query now is locating the elusive file systems.config.js. What pur ...

Incorrect object being returned from Angular 2 HTTP request

For my data fetching from the server, I am using @angular/http get method. Below is the code snippet: private _currentPT: any; public phongtroDetailChange = new Subject(); layPhongtro(id: number): Promise<any> { return new Promise((resolve, reject) ...

Issues retrieving data using Ionic 4 native HTTP plugin result in returning an empty

Currently, I am working on an Ionic 4 project where I am attempting to retrieve a JSON array from a URL using the native HTTP for Ionic. However, when I attempt to fetch the data array from the URL in JSON format, I am met with an empty page. The JSON dat ...

How to Reload the Active Tab in Angular 5?

In my project, I have noticed that a listener in one of the tabs causes the entire tab to refresh, resulting in it displaying information from the first tab until I switch to another tab and then go back. 1) Is there a way to refresh only the current tab? ...

Creating a dynamic component in Angular using the ng-template approach

Exploring Components using ng-template @Component({ template: ` <div>Welcome to the Component!</div> <ng-template #contentTemplate> <div>This is the template content</div> </ng-template> `, }) expo ...

The Axios and TypeScript promise rejection error is displaying an unknown type- cannot identify

Currently, I am encountering an issue where I am unable to utilize a returned error from a promise rejection due to its lack of typability with Typescript. For instance, in the scenario where a signup request fails because the username is already taken, I ...

Dynamic content within an Angular Swiper

Greetings, Experts! I am a newcomer to angular and have successfully created 3 components: Swiper YouTube frame Map display Currently, I am facing a challenge where I need to utilize the swiper component multiple times on the homepage. The first instanc ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

The error message "The file 'environment.ts' is not located within the specified 'rootDir' directory" was encountered during the Angular Library build process

When attempting to access the environment variable in an Angular 9 library, I encountered an error during the library build process. Here is how it was implemented: import { EnvironmentViewModel } from 'projects/falcon-core/src/lib/view-models/envir ...

Issue encountered during rendering: "TypeError: Attempting to access property '_t' of an undefined object" while running a Unit Test using Jest

I spent hours troubleshooting a unit test for my Vue.js component, but no matter how much I searched the internet, I kept encountering this error: console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884 TypeError: Cannot read property ' ...

Exploring Angular2: Incorporating External Plugins with AngularCLI (webpack)

Currently, I am in the process of developing an Angular2 application using AngularCLI with webpack version. A third-party plugin called ScrollMagic is being utilized which comes with optional plugins of its own. The main codebase for ScrollMagic has been i ...

Issue with Angular Router: unable to retrieve route parameters in child paths

Within our main app.component routing, we have the following setup: { path: 'store', loadChildren: './store/store.module#StoreModule', canActivate: [LoginGuard] }, Then, in the module, our routes are defined as follows: const routes: ...

What is the process for creating a new type from a nested part of an existing type?

Currently, my website is being developed with a focus on utilizing code generation to ensure type safety when handling GraphQl queries. Certain components within the application receive a portion of an object as a prop. The specific type structure is outli ...

TypeScript fails to detect errors in setting state with incorrect interface properties in React components

Even though I clearly defined an interface with specific props and assigned that interface to be used in useState, no error is triggered when the state value is set to an array of objects with incompatible props: This is how ResultProps is defined: interf ...

Transforming Bootstrap using Typescript styled components

I have been working on customizing the Navbar in my React app using Typescript's styled components. However, I am facing difficulties in restyling the default styles from Bootstrap that I have copied. Here is an example of the React Bootstrap Navbar c ...

Could not find the 'injectTapEventPlugin' export in the dependencies of Material-UI related to 'react-tap-event-plugin'

Currently, I am working on a project that involves using react, typescript, material-ui, and webpack. An issue has arisen with importing the injectTapEventPlugin function from the dependency of Material-UI, react-tap-event-plugin. The specific error messag ...

Choosing multiple lists in Angular 2 can be achieved through a simple process

I am looking to create a functionality where, upon clicking on multiple lists, the color changes from grey to pink. Clicking again will revert the color back to grey. How can I achieve this using class binding? Below is the code snippet I have tried with ...

Easy steps to bring in type definitions from an npm package using Vite

I am currently developing a package with several ts functions that will be utilized by multiple repositories, including mobile and web applications. In our team, we use vite as our primary build tool, which is also integrated into the repository. Below is ...