如果按钮位于组件A中且元素位于组件B中,则单击显示元素

问题描述 投票:1回答:1

我想在单击按钮时显示div,但它们都在不同的组件中。那么如何在组件之间进行交互。

我对angular4非常新,所以如果有更好的方法可以做到这一点,我将非常感激

这些是html的两个不同组件。

button.component.html

<button class="btn btn-primary" [hidden]="hidden" 
      (click)="hidden = true ">Show Age</button>

text.component.html

     </div> AGE </div>
    <div *ngIf="hidden"> 22 </div>

添加截图

enter image description here

html angular typescript
1个回答
2
投票

您的组件A应该有一个输出事件:

@Output() change = new EventEmitter();
// ...
onClick(){
  this.change.emit();
}

点击按钮发出它:

<button (click)="onClick()">Show Age</button>

并且您的父组件(=包含A和B的组件)应该处理hidden值,将其传递给组件B并在从组件A接收到change事件时更改它。

父组件HTML:

<app-component-a (change)="hidden = !hidden"></app-component-a>
<app-component-b [hidden]="hidden"></app-component-b>

父组件TS:

hidden:boolean = false;

组件B TS:

@Input() hidden:boolean = false;
© www.soinside.com 2019 - 2024. All rights reserved.