Home > Net >  Invoking a method with return from non related component using RXJS or any other option
Invoking a method with return from non related component using RXJS or any other option

Time:06-10

Want to invoke Is Valid from component1.ts and check for the return value and do another logic based on the return value . I have two component

1. Component1.ts
2. Component2.ts

// This is the method in component 2
Component2.ts has a method
Is Valid(): Boolean
{
return true;
}

Needs to invoke the method and return the value

CodePudding user response:

So what you are trying to do is component communication. Since your components are independent, using a service is a valid way to do this.

See this StackBlitz demo. It does pretty much what you're looking for.

CodePudding user response:

Generate a new service:

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



@Injectable({
  providedIn: 'root'
})
export class IsValidService {

  private isValid: boolean = false;


  constructor() { }

  get getIsValid(): boolean {
    return this.isValid;
  }

  set setIsValid(newVal: boolean) {
    this.isValid = newVal;
  }
}

Then from Component1 you can call the getter to get the value:

export class Component1{
  isValidFromComponent2 : boolean;
  constructor(private isValidService: IsValidService) { }
  ngOnInit(){
    this.isValidFromComponent2 = this.isValidService.getIsValid;
  }
}

From component2 you can set the value:

export class Component2{
  constructor(private isValidService: IsValidService) { }
  ngOnInit(){
    this.isValidService.setIsValid = false; //you can add logic here
  }
}
  • Related