html - 从角度 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>
我创建了一个示例。请使用此链接
解决方案
那么在这种情况下,请在服务中使用 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
)
}
工作演示
推荐阅读
- python - 为什么在 scikit-learn 0.23 中“fit”方法的输出发生了变化?
- html - jQuery从点击类中获取不同的值
- android - 反应原生社区 Viewpager 没有透露下一张幻灯片/视图的一部分
- python - 使用 pandas python 将 html 表转换为 csv
- node.js - 如何将篮子总数传递给 Razor 支付后端 NodeJS
- c# - 如何为输入字段使用数据库默认值?
- mysql - Mariadb Explain 语句估计在查找期间将找到的大量行
- python - 时间延迟并跟踪点击次数
- javascript - 单击按钮时如何设置下拉列表的默认值
- android - 新的 Google Play 控制台 - 首次应用发布问题的托管发布,一次发布多个版本