【问题标题】:Reloading a child component from parent without ngOnChanges (Angular)在没有 ngOnChanges (Angular) 的情况下从父组件重新加载子组件
【发布时间】:2021-06-18 19:14:16
【问题描述】:

我正在使用具有输入属性的子组件。

<child [inputprop]="input"></child>

子组件没有实现 ngOnChanges。我想从父级更新组件。最好的方法是什么?

我研究过使用ngIf 并重新渲染组件。有没有更清洁的方法?

<child [inputprop]="input" ngIf="render"></child>

组件

rerender() {
       render=false
       cdRef.detectChanges()
       render=true
}

编辑:我无法更改子组件的代码。我正在寻找更好的方法来做到这一点,而无需更改子组件。

【问题讨论】:

  • 我在这个答案中使用了一些技巧,可能会对您有所帮助stackoverflow.com/a/65531547/9546702
  • 你想要做什么的想法是完全错误的(对不起,坦率地说),相反,我希望让子组件实现 ngOnChanges。
  • 我想让子组件实现它。但我无法更改该代码。我正在尝试在一个大项目中重用一个组件。

标签: angular


【解决方案1】:

您的逻辑非常错误,因为它会破坏组件一次然后重新初始化它。如果您只想重新渲染和触发更改检测,您可以按照以下步骤操作:-

Step1 :- 在您的子组件中注入 ChangeDetectorRef。

constructor(private cd: ChangeDetectorRef){}

Step2 :- 实现一个调用检测子组件变化的公共方法。

public reRender() {
   this.cd.detectChanges();
}

Step3 :- ViewChild 您在父组件中的子组件,例如:-

@ViewChild(ChildComponent) child: ChildComponent;

Step4 :- 从父组件调用该方法。

this.child.reRender();

【讨论】:

  • 感谢您的回答。我知道我的方法很糟糕,这就是我寻找更好解决方案的原因。此外,我无法更改子组件代码,这是我的主要问题。
【解决方案2】:

您可以创建一个“通知程序”类。

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);
  }
}

并像这样使用它

&lt;child [inputprop]="input" [notifier]="notifyHandler.notifier"&gt;&lt;/child&gt;

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>);
}
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 2018-12-11
    • 2021-02-10
    • 1970-01-01
    • 2017-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多