[英]Reloading a child component from parent without ngOnChanges (Angular)
我正在使用具有輸入屬性的子組件。
<child [inputprop]="input"></child>
子組件沒有實現 ngOnChanges。 我想從父級更新組件。 最好的方法是什么?
我已經研究過使用ngIf
並重新渲染組件。 有沒有更清潔的方法?
<child [inputprop]="input" ngIf="render"></child>
零件
rerender() {
render=false
cdRef.detectChanges()
render=true
}
編輯:我無法更改子組件的代碼。 我正在尋找更好的方法來做到這一點,而無需更改子組件。
您的邏輯非常錯誤,因為它會破壞組件然后重新初始化它。 如果您只想重新渲染和觸發更改檢測,您可以按照以下步驟操作:-
第 1 步:- 在您的子組件中注入 ChangeDetectorRef。
constructor(private cd: ChangeDetectorRef){}
Step2:- 實現一個調用檢測子組件變化的公共方法。
public reRender() {
this.cd.detectChanges();
}
Step3:- ViewChild 在父組件中查看您的子組件,例如:-
@ViewChild(ChildComponent) child: ChildComponent;
Step4:- 從父組件調用該方法。
this.child.reRender();
您可以創建一個“通知程序”class。
export class NotifyHandler<T> {
private readonly source$: Subject<T> | BehaviorSubject<T>;
private readonly notifier$: Observable<T>;
constructor(initialValue?: T) {
this.source$ = initialValue ? new BehaviorSubject(initialValue) : new Subject();
this.notifier$ = this.source$.pipe(shareReplay(1));
}
get notifier(): Observable<any> {
return this.notifier$;
}
public notify(value?: T): void {
this.source$.next(value ?? null);
}
}
並像這樣使用它
<child [inputprop]="input" [notifier]="notifyHandler.notifier"></child>
child component
.....
private subscriptions = new Subscription();
@Input()
notifier:Observable<any>;
constructor(props){
this.subscriptions.add(this.notifier.subscribe(event=> ...handle update logic...));
}
ngOnDestroy(){
this.subscriptions.unsubscribe();
}
....
parent component
...
public notifyHandler= new NotifyHandler<any>();
onChildMustUpdate(){
notifier.notify(<data if any required>);
}
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.