首页 > 解决方案 > 从角度 4 中的另一个组件按钮单击触发按钮

问题描述

我有组件 A 按钮,它在单击时显示表单,组件 B 按钮显示名称。我想在单击 componentB 按钮时触发 ComponentA 按钮并显示表单

组件 HTML

<section>
   <button (click)="toggle()">Click Here To Search</button>

 <div *ngIf="!showInput">
    <input type="text"/><br/>
  <button type="submit">Submit</button>
  <button>Cancel</button>
</div>
</section>

组件A TS

  showInput = true; 
//...
  toggle() {
            this.showInput = !this.showInput;
           }

组件B HTML

<button (click)="toggleText()">Add Fruit</button>

<div *ngIf="showText">Apple</div>

我创建了一个示例。请使用此链接

示例链接

标签: htmlangulartypescript

解决方案


那么在这种情况下,请在服务中使用 rxjs BehaviorSubject,以便您的整个应用程序可以使用该变量并相应更新,如下所示

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class Service {
  toggle: BehaviorSubject<boolean> = new BehaviorSubject(false);
  toggle$ = this.toggle.asObservable();
}

在你的我的文本组件中

toggleText() {
  this.showText = !this.showText;
  this.service.toggle.next(this.showText)
}

并在您的 FormsComponent 中

showInput;

ngOnInit() {
  this.service.toggle$.subscribe(
    toggle => this.showInput = toggle
  )
}

工作演示


推荐阅读