0

I have component A button which displays form on click and component B button to show name. I want to trigger ComponentA button and display form when componentB button is clicked

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>

componentA TS

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

componentB HTML

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

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

I have created an example.Please use this link

Example Link

2
  • Don't you want to show the name of the fruit or you just want to show the form if addFruit is clicked or want to show both simultaneously. As you are not clear what all exactly you want Commented Nov 1, 2018 at 23:01
  • want to show both Commented Nov 2, 2018 at 0:22

1 Answer 1

2

Well in that case make use of rxjs BehaviorSubject in a service, so that your entire application can make use of the variable and will update accordingly, like below

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();
}

and in your my text component

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

and in your FormsComponent

showInput;

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

Working demo

Sign up to request clarification or add additional context in comments.

3 Comments

Worked like a charm @Suryan. I have a question for you that when using NgRx, Is it the good approach using service ?
@JesseW sorry, don't have the experience of ngrx maybe other can help you out on this
Ok. Thank you so much @Suryan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.