【问题标题】:How can I hide a HTML element on a grandfather component after a button on a grandchild component is clicked?单击孙组件上的按钮后,如何隐藏祖组件上的 HTML 元素?
【发布时间】:2021-07-24 00:35:12
【问题描述】:

我有一个祖父组件,它显示一条消息,指出必须更新孙子组件上的字段。

一旦用户更新值并点击按钮,祖父母的 HTML 元素必须立即消失。

我的解决方案的简化模型如下:

<div [hidden]="buttonPressedOnGrandchild">
    <p>You must update the field X</p>
</div>

我需要将孙子组件的 buttonPressedOnGrandchild 的值设置为 true。或者使用其他解决方案来隐藏元素。

我找到了父母>孩子和孩子>父母沟通的解决方案,但不适用于祖孙沟通。

【问题讨论】:

  • child->parent->grandparent 方法可以是一种。另一个可以使用带有 BehaviorSubject 的服务。
  • 谢谢,我最终通过 EventEmitter 与孩子>父母>祖父母沟通,但对于更复杂的组件关系结构,接受的答案应该是最佳解决方案。

标签: html angular angular-components


【解决方案1】:

解决方案是服务。使用该服务设置孙子点击时的值,并让祖父订阅该值,以便在它发生变化时得到更新。

GrandfatherToGrandChildService

private buttonPressedOnGrandchild: Subject<boolean> = new Subject<boolean>();

// return the Subject as an Observable in order to be able to subscribe to it
public get buttonPressed(): Observable<boolean> {
    return this.buttonPressedOnGrandchild.asObservable();
}

// set the current value
public set buttonPressed(value: boolean) {
    this.buttonPressedOnGrandchild.next(value);
}

GrandfatherComponent TS

constructor(private grandfatherToGrandChildService: GrandfatherToGrandChildService){

}

ngOnInit(): void {
    // subscribe to the value and refresh the local variable whenever it changes
    this.grandfatherToGrandChildService.buttonPressed.subscribe( value => {
        this.buttonPressedOnGrandchild = value;
    });
}

GrandChildComponent TS

constructor(private grandfatherToGrandChildService: GrandfatherToGrandChildService){
}

onClick(): void {
    this.grandfatherToGrandChildService.buttonPressed = true;
}

【讨论】:

  • 谢谢,我最终使用了子>父>祖父通信的解决方案,但我相信您的解决方案最适合更复杂的组件关系结构。
猜你喜欢
  • 1970-01-01
  • 2016-06-12
  • 2017-08-11
  • 1970-01-01
  • 2021-11-22
  • 2020-05-09
  • 2020-04-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多