繁体   English   中英

在 Angular 14 中从父级重新加载多个子组件

[英]Reloading multiple child component from parent in Angular 14

我在 Angular 中从父组件重新加载我的子组件时遇到问题。

这是我想做的一个例子。

这是我的子组件

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();
  }
}

这是我的父组件:

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();
  }
}

父组件 HTML:

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

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

主要问题是,如果我多次使用我的子组件,并尝试单击“更新”按钮,它只会更新我在父组件中使用的子组件之一,但我想更新父组件中的所有相同子组件组件,这里是当你点击“更新”按钮时发生的事情,只有第一个值会改变,而不是两个。

在此处输入图像描述

我该如何解决???

您可以使用 @ViewChildren 和 QueryList 来执行您要查找的操作。

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

你的 function 看起来像:

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

如果您希望您的子组件自行更新 - 如对原始帖子的评论所述 - 这是您可以执行的操作的示例,因此您甚至不需要更新按钮:

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
  }
}

您可以在不使用按钮的情况下执行的另一种选择是将@Input与 ticks 属性一起使用,该属性通过输入更新父级的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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