[Fixed] Getting value from another component in Angular 10


I have 2 components called subscription.ts and home.ts
On subscription I have a functions which checks if user is subscribed or not. The function is as follows

checkSubscriptionStatus(): any {

    this.apiService.getSubscriptionStatus().subscribe((getData: any) => {
        this.subsStatus = getData.data.subscription.status;
      error => {
        this.subsStatus = '';
        if (error.status !== 401) {
          this.commonService.showNotificationMessage('Something went wrong. Try again!', 'text-danger');

I want to use the value of this.subsStatus on the view of home.ts, that is on home.html. I tried to add <app-subscription></app-subscription> which is the component selector for subscription.ts but it is showing the whole subscription.html view. I just want to use the variable. How can I do that? Thanks in advance.


I think, I have Two solutions for you, Here is the first one. It is little complex.

Way 1:
Firstly, you can use a middle service which will share data between 2 classes.
The service will look like below=>

import { EventEmitter, Injectable } from "@angular/core";

  providedIn: "root"
export class MyService {
  mystatusChanged: EventEmitter<any> = new EventEmitter();
  mystatus: any;
  constructor() {}
  get data(): any {
    return this.mystatus;
  set data(val: any) {
    this.mystatus = val;

Here, you can a get and set method for data. At the same time when data updated an event will emit. So, you can use that service in both subscription.ts and home.ts file. In subscriptionfile you will set the data of that service inside checkSubscriptionStatus function. On the other hand, you have to subscribe the event in the home.ts like below=>

In subscription.ts File:

constructor(private mysrvc:MyService){
checkSubscriptionStatus(): any {
       this.mysrvc.data='Active Status';  //set your status.

In home.ts File:

constructor(private mysrvc:MyService){

Now, the thing is you can call checkSubscriptionStatus of by creating a object of SubscriptionComponent and home component will get the updated value.

Demo Sample Stackblitz Link.

Way 2:
You can use @ViewChild,hidden and @Output to achieve it=>


import { Component, EventEmitter, Input, Output } from '@angular/core';
  selector: 'subscription',
  template: `<h1>subscription</h1>`,
  styles: [`h1 { font-family: Lato; }`]
export class SubscriptionComponent  {
   @Output() myUpdatedStatus = new EventEmitter<string>();
     this.myUpdatedStatus.emit("Active Status");

For home HTML

<subscription #child hidden (myUpdatedStatus)="showStatus($event)"></subscription>
<br><button (click)="myClick()">Click Me!!</button>

For Home TS:

export class AppComponent  {
  @ViewChild('child') child:SubscriptionComponent;

Demo Sample Stackblitz Link.

Leave a Reply

(*) Required, Your email will not be published