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!