简体   繁体   中英

Call function from one component from a component Angular

I'm a beginner in Angular. I've been facing this issue with calling a method in a component from a component, which they are not related to. I followed a lot of tutorials on the internet but haven't found the solution.

So the detail is: There are 2 unrelated components. The first component has a button and if I click that button, the string from the first component should be sent to a function in the second component and in that function It should display the string into the console. But the problem I'm facing here is that the function is called only once before I click and it just displays the value "111" which is the default value. Please help me

First component:

 export class FirstComponent implements OnInit{ constructor(location:Location, private renderer : Renderer2, private element : ElementRef, private router: Router, private httpClient: HttpClient, private servic: MainService) { } clickMe() { this.servic.sendMessage("001"); } }

Second component:

 export class SecondComponent implements OnInit { clickEventSubs:Subscription; constructor(public servic: MainService, private spinner: NgxSpinnerService, private router: Router){} this.clickEventSubs = this.servic.receiveMessage().subscribe(message => { this.toggle(message); }) public toggle(state: string){ console.log(state); } }

Shared service:

 @Injectable({ providedIn: 'root' }) export class MainService { private message = new BehaviorSubject<string>("111"); sendMessage(mess:string) { this.message.next(mess); } receiveMessage(): Observable<any> { return this.message.asObservable(); } }

When relationships between component is Child > Parent - Share date via @viewChild()

In First Component, Use @ViewChild() and pass second component name as an argument -

@ViewChild(SecondComponent) secondChildView!: SecondComponent;

Then call the second component's function in the first component's function -

 import {ViewChild} from '@angular/core';

 export class FirstComponent implements OnInit{
 @ViewChild(SecondComponent) secondChildView!: SecondComponent;

 constructor() {}
 
   clickMe() {
     this.secondChildView.toggle('001'); 
  }
}

Whenever you call clickMe function it will call the toggle function of second component and you will get the value in toggle function from the first component.

export class SecondComponent implements OnInit {

 constructor(){} 

 public toggle(state: string){
  console.log(state);
 }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM