【问题标题】:Passing boolean value is not getting shared from one component to another - Angular传递布尔值不会从一个组件共享到另一个组件 - Angular
【发布时间】:2020-06-11 14:59:29
【问题描述】:

这只是简单的用例,但不要得到我所缺少的。

我有组件 A 和组件 B。使用 eventEmitter 通过点击事件将布尔值从 componentB 传递到 componentA,以显示/隐藏 componentA 中的特定 div。

到目前为止

组件B

public showLayOut = false;
@Output() passThisValue = new EventEmitter<boolean>();

ngOnInit(): void {
    this.showLayOut = false;
}

triggerEventToPassBoolVal() {

    this.someService(baseLink).subscribe((data) => {
        if (data[0].status === true) {
            this.showLayOut = true;
            if (this.showLayOut) {
                this.passThisValue.emit(this.showLayOut);
            }
        }
    })
}

组件A.html

<div *ngIf="showLayOut">
   <p>Show this div if emitted value is true, otherwise hide</p>
</div>

谁能帮我指出我做错了什么?如果可能,请分享任何现有的 stackblitz 工作示例

注意:我使用这样的表单提交数据(ngSubmit)="OK(data)" 谢谢

【问题讨论】:

  • 你能把你的代码分享给stackblitz吗,把链接贴在这里。
  • @truonghungit stackblitz.com/edit/… 在 stackblitz 中出现错误。但我在我的项目中没有看到这一点
  • @worstCoder,你需要这样吗? stackblitz.com/edit/angular-ivy-zatwqo
  • @ManirajMurugan 感谢您的提醒。但我在提交表单时也是这样做的。我已经更新了我的问题。
  • @worstCoder,我看不到任何与表单相关的代码。你能用与表单相关的代码更新 stackblitz 吗?这样就很容易理解你的真正问题..

标签: angular eventemitter


【解决方案1】:

如果 componentAcomponentB 的父组件。我有那个解决方案。例如:

  import { Component, OnInit, ViewContainerRef } from '@angular/core';
  
  // componentB.compoent.ts

  getParentComponent() {
    return this.viewContainerRef['_data'].componentView.component.viewContainerRef['_view'].component;
  }
  
  changeBooleanvalueMethod () {
     this.getParentComponent().showLayOut = true; // showLayOut is componentA variable
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-11
    • 2018-02-19
    • 2020-07-26
    • 2021-10-31
    • 2022-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多