【问题标题】:How to use share data between two components如何在两个组件之间使用共享数据
【发布时间】:2021-02-22 08:33:53
【问题描述】:

我在其他两个组件(购买组件和出售组件)中使用了一个共享组件(一个带有“继续”按钮的输入搜索栏)。 我想在我的购买组件中隐藏我的搜索栏组件的“继续”按钮,同时在我的销售组件中显示它。 为了实现这一点,我在购买组件中使用了@Input continueButtonCheck,它隐藏了购买模块组件上的按钮,但也将其隐藏在销售组件中。我需要相同的 continueButtonCheck 并将其传递给我的其他组件(销售组件)。

共享组件如下所示:

(共享)search-bar-component.html 文件:

<input />
<button *ngIf="continueButtonCheck">continue</button> 

这用于我的其他两个组件。

一个例子可以在这里找到:

https://stackblitz.com/edit/angular-ivy-jaqbnn?file=src%2Fapp%2Fbuy%2Fbuy.component.ts

我面临的问题是我不知道如何访问我的销售组件中的“continueButtonCheck”属性。

【问题讨论】:

  • 什么时候需要?当搜索组件中发生某些事情时,您可以@Output 它,例如键入或按下按钮。
  • @Input 属性未定义,因此除非在父组件中明确设置,否则不会呈现按钮。您可以在 search.component.ts 中定义一个默认值而不是 @Input() continueSearchButton = true;。我已经修改了你的Stackblitz
  • 是的,它按照我想要的方式工作,谢谢:)

标签: javascript angular typescript


【解决方案1】:

这是因为 @Input() continueSearchButton 默认未定义。所以&lt;button *ngIf="continueSearchButton"&gt;Continue&lt;/button&gt;continueSearchButton 会是假的,它会隐藏按钮。

因此您可以将@Input() continueSearchButton = true; 默认设置为true。如果你需要隐藏按钮,你可以像在购买组件中那样做

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-24
    • 2013-02-25
    • 1970-01-01
    • 2019-02-11
    • 2017-09-29
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多