我有两个部分,一个父母和另一个孩子。
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。
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.
}
}
}
通过使用主题,每当单击按钮时,您就可以建立从父母到孩子的连接。希望此答案有帮助!干杯:)
([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(); } }