我有组件 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
)
}
工作演示
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句