Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

186
Visualizações
How to call a function from another component using click event

I want to call a function of another component which has no relation on the click

servive File

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

@Injectable()
export class ShareDetailsService {
  clicked : boolean = false;
  constructor() { }

}

component 2

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {

  constructor(shareDetailsService : ShareDetailsService) { }

  ngOnInit() {
    if(shareDetailsService.clicked){
      console.log("clicked");
    }
  }

Component 1

@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {

  constructor(shareDetailsService : ShareDetailsService) { }

  ngOnInit() {
    if(shareDetailsService.clicked){
      console.log("clicked");
    }
  }
  someFunction(){
  }
  

Component 1 Html

<div (click)="someFunction()"></div>

When I call the function using the click event it should call the function of the another component , I created a service file and where I am able to change the boolean variable.

I Want to call the function when there is a change in the boolean Variable rather than calling the function on ngOnit()

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use a subject to subscribe to it.

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs' 
@Injectable()
export class ShareDetailsService {
  clicked$ = new Subject();    
}

// Any component can post and subscribe to it

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {

  constructor(shareDetailsService : ShareDetailsService) {
    this.sharedDetailsService.clicked$.subscribe(() => console.log('clicked')
  }

  onClick() {
     this.sharedDetailsService.clicked$.next(); // dispatch the click
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda