更新子组件的最佳方法是: ngOnChanges()
ngOnChanges():“生命周期挂钩,当指令的任何数据绑定属性发生更改时都会调用。定义ngOnChanges()方法来处理更改。”我们使用此生命周期挂钩来响应对@Input()变量的更改。
示例:
import { Component,Input,OnChanges } from "@angular/core";
@Component({
selector: "child-component",templateUrl: "./child-component.html"
})
export class MyComponent implements OnChanges {
@Input() someInput: string;
constructor() {}
ngOnChanges() {
/**********THIS FUNCTION WILL TRIGGER WHEN PARENT COMPONENT UPDATES 'someInput'**************/
//Write your code here
console.log(this.someInput);
}
}
按如下所示在父组件中使用子组件
<child-component [someInput]="inputValue"></child-component>
,
我们还可以使用*ngIf
和setTimeout
从父级重置子级组件,而无需更改子级组件。
.template:
.ts:
show:boolean = true
resetChildForm(){
this.show = false;
setTimeout(() => {
this.show = true
},100);
}
当我们无法控制子组件(例如第三方库组件)时,这特别有用。
,
如果您在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.
}
}
}
通过使用“主题”,可以在单击按钮时建立从父母到孩子的连接。
希望这个答案有帮助!干杯:)
,
您可以添加输入以更新组件,或者在子级中添加可以在代码中调用的更新功能。使用@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();
}
}
本文链接:https://www.f2er.com/3160063.html