简体   繁体   中英

Reloading multiple child component from parent in Angular 14

I have a problem with reloading my child component from parent component in Angular.

Here is an example of what I want to do.

This is my child component

import { Component } from "@angular/core";

@Component({
  selector: "app-child",
  template: `<p> {{ticks}} </p>`,
  styleUrls: ["./child.component.css"]
})
export class ChildComponent {
  ticks = Date.now().valueOf();

  constructor() {}

  update(): void {
    this.ticks = Date.now().valueOf();
  }
}

And here is my parent component:

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css'],
})
export class ParentComponent implements OnInit {
  @ViewChild(ChildComponent, { static: false }) childC: ChildComponent;
  showChild: boolean = true;
  constructor() {}

  ngOnInit() {}

  onUpdateChild() {
    this.childC.update();
  }
}

Parent Component HTML:

<p>
    parent works!
    <button (click)="onUpdateChild()">update</button>
    <app-child *ngIf="showChild"></app-child>

    <app-child *ngIf="showChild"></app-child>
</p>

The main problem is that if I use my child component multiple time, and trying to click on “update” button, it just updates one of my child component that is used in parent component, but I want to update all same child component in parent component, here is what happens when you click on “update” button, only first value will change, not both.

在此处输入图像描述

How can I fix it???

You can use @ViewChildren and QueryList to do what you are looking for.

@ViewChildren(ChildComponent) childrenC:; QueryList<ChildComponent>;

And your function would look like:

onUpdateChild() { //I would rename it to onUpdateChildren
    if(this.childrenC) { 
       this.childrenC.forEach((childC: ChildComponent) => {
          this.childC.update();
       });
    }
}

If you wanted your child component to update on it's own - as stated by a comment to your original post - this is an example of what you could do so you wouldn't even need the update button:

import { Component, OnInit } from "@angular/core";

@Component({
  selector: "app-child",
  template: `<p> {{ticks}} </p>`,
  styleUrls: ["./child.component.css"]
})
export class ChildComponent implements OnInit {
  ticks = Date.now().valueOf();

  constructor() {}

  ngOnInit(): void {
    setInterval(() => {
        this.ticks = Date.now().valueOf();
    }, 1000); //updates every 1 second
  }
}

Another option you can do without using a button is to use @Input with the ticks property that updates the value from the parent through an input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM