Как перезагрузить или обновить только дочерний компонент в Angular 8 - PullRequest
0 голосов
/ 05 ноября 2019

У меня есть два компонента: один родительский и другой дочерний.

HTML-часть

<div>
  <div class="row col-md-12">
    <div class="col-md-4">
       <!-- Some HTML Code of Parent component over here -->
    </div>
    <div class="col-md-8">
      <child-component></child-component>
    </div>
 </div>
 <button class="button" (click)="reloadOnlyChild($event)">Reload Child</button>
</div>

Теперь, при нажатии этой кнопки, я хочу, чтобы единственный дочерний элемент получил перезагрузку или обновление.

Часть TS

reloadOnlyChild(event){
  // I want to reload the child from here.
}

Я искал в Интернете, я получаю Vue или React, но не Angular.

Ответы [ 2 ]

1 голос
/ 05 ноября 2019

Вы можете добавить вход для обновления компонента или добавить функцию обновления в дочерний элемент, который вы можете вызвать в коде. Использование @ViewChild для вызова дочерней функции обновления из родительского. Как это

(https://stackblitz.com/edit/angular-updatechild):

Ребенок:

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

@Component({
   selector: "app-child",
   templateUrl: "./child.component.html",
   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-parrent",
 templateUrl: "./parrent.component.html",
 styleUrls: ["./parrent.component.css"]
})
export class ParrentComponent implements OnInit {
  @ViewChild(ChildComponent, { static: false }) childC: ChildComponent;
  showChild: boolean = true;
  constructor() {}

  ngOnInit() {}

  onUpdateChild() {
    this.childC.update();
 }
}
1 голос
/ 05 ноября 2019

Скажите, если у вас есть форма в Child.Component.ts, и если вы хотите сбросить ее с parent component, вы можете установить связь между родителем и ребенком, используя Subject.

Parent.Component.html

<child-component [resetFormSubject]="resetFormSubject.asObservable()"></child-component>
<button (click)="resetChildForm()"></button>

Parent.Component.ts

import { Subject } from "rxjs";
resetFormSubject: Subject<boolean> = new Subject<boolean>();

resetChildForm(){
   this.resetFormSubject.next(true);
}

Child.Component.ts

import { Subject } from "rxjs";
@Input() resetFormSubject: Subject<boolean> = new Subject<boolean>();

ngOnInit(){
 this.resetFormSubject.subscribe(response => {
    if(response){
     yourForm.reset();
    // Or do whatever operations you need.
  }
 }
}

Используя тему, вы можете установить связь между родителем и ребенком при каждом нажатии кнопки.

Надеюсь, этот ответ поможет! Ура :) 1023 *

...