我正在使用一个具有输入属性的子组件。
<child [inputprop]="input"></child>
子组件未实现ngOnChanges。我想从父级更新组件。最好的方法是什么?
我已经研究过使用ngIf
并重新渲染组件。有更干净的方法吗?
<child [inputprop]="input" ngIf="render"></child>
组件
rerender() {
render=false
cdRef.detectChanges()
render=true
}
编辑:我无法更改子组件的代码。我正在寻找在不更改子组件的情况下实现这一点的更好方法。
您可以创建一个"notifier"类。
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>);
}
...
您的逻辑非常错误,因为它会破坏组件一次,然后重新初始化它。如果您只想重新渲染并触发更改检测,您可以按照以下步骤操作:-
步骤1:-在您的子组件中注入ChangeDetectorRef。
constructor(private cd: ChangeDetectorRef){}
步骤2:-实现一个公共方法,该方法调用检测子组件中的更改。
public reRender() {
this.cd.detectChanges();
}
步骤3:-ViewChild您的子组件在父组件中,如:-
@ViewChild(ChildComponent) child: ChildComponent;
步骤4:-从父组件调用该方法。
this.child.reRender();