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

Limiting the use of TypeScript ambient declarations to designated files such as those with the extension *.spec.ts

In my Jest setupTests file, I define several global identifiers such as "global.sinon = sinon". However, when typing these in ambient declarations, they apply to all files, not just the *.spec.ts files where the setupTests file is included. In the past, ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

Angular 5 - Deleting DOM Elements Causes View to Remain Stale

I am experiencing an issue with a tag type search functionality on my website. The search has two columns in the view, with the right column for categories and the left for subcategories. When a user clicks on a category tag, I use buttons to display a sel ...

Experimenting with the routerLink directive in Angular 2

Currently, I am in the process of testing routing functionality. As part of this, I have moved my navbar to a separate component called MdNavbar, which primarily consists of HTML and CSS. The RouteConfig is located in another component where MdNavbar is in ...

Scrolling with React Event

I am attempting to create a scrollbar that only appears when I scroll within a particular area using React. I am utilizing debounce and useState in my implementation. The issue: When I reach the end of the scroll, the event continues to repeat indefinitel ...

Ways to verify if a function has completed execution and proceed to invoke another function

I am seeking to verify if a user has chosen an item from the ngFor form and then redirect them to another page upon submitting the form with the updated value. HTML: <mat-select placeholder="Treatment" [(ngModel)]="model.TreatmentA" name="TreatmentA" ...

Guide on how to display matching options in an input box using HTML datalist based on user input at the beginning

I am a beginner in React and I am looking to create an autocomplete suggestion box for a text input field. I want the suggestions to only match the first letters of the available options, unlike the current behavior of HTML's <datalist>. Althou ...

Webpack and React.js: Additional loaders might be required to manage the output generated by these loaders

An error occurred while parsing the module in ./productFlow/index.tsx at line 3, column 12. The file was processed with the following loaders: * ./node_modules/awesome-typescript-loader/dist/entry.js. It seems like an additional loader may be needed to h ...

Angular 16 SSR encounters a TypeError when the 'instanceof' operator is used on a value that is not an object

I have been facing an issue while updating my Angular application from version 15 to 16. Everything seems to work fine with Angular, including building for Angular Universal without any errors. However, when I attempt to serve using npm run serve:ssr, it t ...

Changing the text color of mat-chips in Angular Material

Having a mat-chip-set and multiple mat-chip elements with a custom product-chip class: <mat-chip-set> <mat-chip class="product-chip" *ngFor="let category of categories"> {{category}} </mat-chip> </mat-chip-s ...

Angular2 API call error: The function .map defaultOptions.merge is not recognized

When attempting to call the API using the post method, I encountered the following error message: this._defaultOptions.merge is not a function ... I looked into some solutions and tried importing the following without success: import 'rxjs/add/ope ...

Struggling with the functionality of Angular Material Layout Directives

Looking to implement the Child-Alignment feature in Angular Material but running into some issues. Details available here: https://material.angularjs.org/latest/layout/alignment Despite trying to import import { LayoutModule } from '@angular/cdk/l ...

Clearing a leaflet layer after a click event: Step-by-step guide

When working with my map, I attempt to toggle the layer's selection using a mouse click. Initially, my map looks like this: Upon clicking a layer, my goal is to highlight and select it: If I click on a previously selected layer again, I want to dese ...

Strategies for Implementing Pagination in an Angular 2 HTML Table Without the Use of Third-Party Tools

I have an HTML table that displays basic details along with images. I am looking to implement pagination for this table in Angular 2. Are there any alternatives to using ng2-pagination? ...

Customize YouTube iframe styles in Angular 4+ with TypeScript

Has anyone been successful in overriding the style of an embedded YouTube iframe using Angular 4+ with TypeScript? I've attempted to override a CSS class of the embed iframe, but have not had any luck. Here is the URL to YouTube's stylesheet: ...

A circular reference occurs when a base class creates a new instance of a child class within its own definition

My goal is to instantiate a child class within a static method of the base class using the following code: class Baseclass { public static create(){ const newInstance = new Childclass(); return newInstance; } } class Childclass ex ...

What is the process for setting up a single timer in a non-singleton application service?

My goal is to send a GET request every X seconds. To achieve this, I have implemented a timer in the constructor of a service which is then injected into a component for use. I want the service (as a singleton) to handle scheduling the GET requests at regu ...

Issue with launching Angular 6 project

I attempted the solution from this link, but unfortunately, it did not work for me. I have cloned a project from GitLab and am attempting to run it. First, take a look at the output of my ng version command: . The project is based on Angular 6 and is ava ...

What is the best way to maintain scrollbars on mobile devices?

I'm currently building a cross-platform application using Angular 4 that needs to work seamlessly on both mobile and desktop devices. Is there a special trick to prevent the scrollbars from disappearing when viewing this page on a mobile browser? I&ap ...

Encountering "Angular Reactive forms - FormArray - Unable to locate control with specified path" error upon initial loading

Encountering some Cannot find control with path errors while attempting to utilize a basic Reactive Form and FormArray. Component.ts ngOnInit() { this.newForm = this.fb.group({ currencyExchangex: this.fb.array( [this.fb.group({ rateNumeri ...