Modify the property of the ChildComponent by utilizing the ViewChild method

I recently started exploring Angular and I've been experimenting with ViewChild and ViewChildren. In one scenario, I have a property called today = new Date() in my Component2. I'm accessing this property in Component1 using ViewChild and continuously updating the time using setInterval() every second.

Next, I created multiple instances of Component2 using *ngFor directive. However, I noticed that only the initial Component2's today property is being updated while the rest remain unchanged.

Below is the code snippet:

Component1.ts

import{Component,ViewChild,ElementRef,AfterViewInit,OnInit,ViewChildren,QueryList} from"@angular/core";

import { Component2 } from "./Component2";

@Component({
  selector: "comp1",
  templateUrl: "./Component1.html"
})
export class Component1 implements AfterViewInit {
  @ViewChild(Component2) myComponent2: Component2;

  public Component2Array: Array<String> = [
    "Paragraph one",
    "Paragraph Two",
    "Paragraph Three",
    "Paragraph Four"
  ];

  ngAfterViewInit(): void {
    console.log("Component 1 => AfterViewInit", this.myComponent2);
    setInterval(()=>
    {
      this.myComponent2.today = new Date();
    }) 
  }
}

... (a similar format for Component1.html, Component2.ts, and Component2.html can be followed)

If you have any insights on why only the first Component2's today property is updating, please share your thoughts. Example here

Thank you for your help!

Answer №1

Solved the issue on my own by identifying an error in my code. I mistakenly used ViewChild instead of ViewChildren. Made the following changes:

@ViewChild(Component2) myComponent2: Component2;

was changed to

@ViewChildren(Component2) myComponent2: QueryList<Component2>;

Also, updated the code snippet from:

setInterval(()=>
{
  this.myComponent2.today = new Date();
})

to

setInterval(() => {
      this.components.forEach((element) => (element.today = new Date()));
    });

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

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

RXJS buffering with intermittent intervals

Situation: I am receiving audio data as an array and need to play it in sequence. The data is coming in continuously, so I am using an observable to handle it. Since the data arrives faster than it can be played, I want to use a buffer to store the data w ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

What is the process for defining an opaque type in programming?

[ This is not this ] Take a look at this snippet of code: interface Machine<OpaqueType> { get(): OpaqueType, update(t: OpaqueType); } const f = <U, V>(uMachine: Machine<U>, vMachine: Machine<V>) => { const u = uMach ...

The animation of the splash screen in Angular is quite jarring and lacks fluidity

I am experiencing some issues with my angular splash screen animation. It works perfectly when there is no activity in the background, but when I simulate a real-life application scenario, the animation becomes stuttered, choppy, or sometimes does not anim ...

Utilize *ngIf to conceal a row within a material table

I'm struggling with hiding a row after clicking a button in the mat-table. I can't figure out where to place the *ngIf directive. I attempted using it on ng-container, but it didn't work as expected. Below is the excerpt from my HTML file. ...

Unit testing in Angular ensures that a property is always defined and never undefined

I'm struggling to understand why this basic test isn't functioning properly. BannerComponent is not supposed to display a welcome message upon construction Expected 'welcome' to be undefined. // Component @Component({ selector: &ap ...

Angular selects the initial three arrays out of an array

In my code, I have a collection of arrays that are nested within another array. My task is to extract the first three arrays from this collection. For instance, consider the following example: [{[1]},{[2]},{[3]},{[4]}] I apologize for not presenting a p ...

Sorry, I am not able to perform this task as it involves paraphrasing code snippets which can lead to functional changes and potential errors in the code. I recommend seeking assistance from a developer or programmer to

I encountered an issue while trying to convert an HTML file to a PDF file in my project. Can anyone provide guidance on how to resolve this problem? npm install jspdf DownloadCvCompanent.ts: import { Component, ElementRef, OnInit, ViewChild } from '@ ...

Anticipated the object to be a type of ScalarObservable, yet it turned out to be an

When working on my Angular project, I utilized Observables in a specific manner: getItem(id): Observable<Object> { return this.myApi.myMethod(...); // returns an Observable } Later, during unit testing, I successfully tested it like so: it(&apos ...

Error encountered by Angular's Injector in the AppModule when attempting to access the HttpHandler component

I have been successfully running an app for the past few months with no issues. Now, I am exploring the idea of moving some common services into a library that can be utilized by other applications. For this project, I decided to avoid using Angular CLI t ...

The error message "pipe does not exist on type" is encountered when attempting to use pipes with RxJS 6

I am in the process of upgrading my Angular 4 to Angular 6 application, which includes several RxJS operators. I attempted to pipe them together but encountered issues with the syntax. The problem arises specifically on the fifth pipe. Can someone please a ...

The JSON creation response is not meeting the expected criteria

Hello, I'm currently working on generating JSON data and need assistance with the following code snippet: generateArray(array) { var map = {}; for(var i = 0; i < array.length; i++){ var obj = array[i]; var items = obj.items; ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Ways to manage an rxjs observable reaction that may potentially have no data?

Currently, I am working with Angular2 and Ionic2 using typescript and have a requirement to manage responses from the backend service. The response may either be empty with http status 200 or it could be a json object containing an error message property ...

There is no assigned value in scope for the shorthand property. You must either declare one or provide an initializer

I'm just starting out with TypeScript. Encountering the error 'No value exists in scope for the shorthand property 'firstName'. Either declare one or provide an initializer.' while using Prisma with Next.js to create a new user in ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

When creating a new instance of the Date object in Javascript, the constructor will output a date that is

In my project using TypeScript (Angular 5), I encountered the following scenario: let date = new Date(2018, 8, 17, 14, 0); The expected output should be "Fri Aug 17 2018 14:00:00 GMT-0400 (Eastern Daylight Time)", but instead, it is returning: Mon Sep ...

Mapping a Tuple to a different Tuple type in Typescript 3.0: Step-by-step guide

I am working with a tuple of Maybe types: class Maybe<T>{ } type MaybeTuple = [Maybe<string>, Maybe<number>, Maybe<boolean>]; and my goal is to convert this into a tuple of actual types: type TupleIWant = [string, number, boolea ...

Exploring the elements within the ContentChildren directive in Angular

Presenting my component: import { Component, OnInit, ContentChildren, QueryList } from '@angular/core'; import { IconBoxComponent } from '../icon-box/icon-box.component'; @Component({ selector: 'app-three-icon-box', temp ...