Retrieve the public variable of a child page from the parent page

Is there a way to access the public variable offlineArticlesCount from an inner child page within the parent page?

Please note: Each of the 3 components mentioned below has its own set of modules.

myPage.html - Parent Page

 <picks *ngFor="let pick of pickData" [data]="pick"></picks>
 <p>{{instance.offlineArticlesCount}}</p> //How can I achieve this?

myPage.ts

 @ViewChild(DownloadOfflineArticleComponent) instance: DownloadOfflineArticleComponent;

picks.html

<download-offline-article [data]="data" (onDownloadOfflineArticle)="downloadOfflineArticle($event)"></download-offline-article>

download-offline-article.ts - Inner Child Component

export class DownloadOfflineArticleComponent {
   offlineArticlesCount: number = 0;
   constructor() {} 

downloadOfflineArticle() {
    this.articleService.downloadOfflineArticle(this.data.id)
      .subscribe((res: any) => {
        this.onDownloadOfflineArticle.emit(true);

        this.localCacheService.clearMyLibraryPageCacheGroup().then(() => {
          this.getAllMyPurchasedOfflineArticles().subscribe((res: any) => {
            this.offlineArticlesCount = res.count; // This is where the update occurs
          },
            error => { },
            () => { });
        });
      },
      error => { },
      () => { });
  }
}

Answer №1

There are multiple ways to access the property from a child component, depending on where you want to use it.

If you just need to display it in the view, using a template reference variable is a good option:

<picks *ngFor="let pick of pickData" [data]="pick"></picks>
<p>{{ offlineArticle.offlineArticlesCount }}</p>
<download-offline-article #offlineArticle ..."></download-offline-article>

This way, you avoid creating an instance of the child component in your parent's component code.

If you need to use the property in your component code, using ViewChild to obtain the instance of the child component is recommended:

// Parent component code...

@ViewChild(DownloadOfflineArticleComponent) childComponent: DownloadOfflineArticleComponent; 

You can then access it in the view like this:

<!-- Your view -->
{{ childComponent?. offlineArticlesCount}}

EDIT

If you have a complex hierarchy of components, consider utilizing a shared service to store and retrieve shared information easily across different components or pages in your application.

Answer №2

Only need a single line:

@ViewChild(DownloadOfflineArticleComponent) childComponent: DownloadOfflineArticleComponent;

You can then retrieve all the accessible variables using

{{ childComponent?.offlineArticlesCount }}

Answer №3

Once you have clarified the hierarchy of your components by editing your question, I believe the most effective solution to your issue would be to implement a shared service for data sharing between components:

// Implementation of the shared service:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Observable } from 'rxjs';

@Injectable()
export class SharedDataService {

    private articleCountSubject: BehaviorSubject<any> = new BehaviorSubject({});    

    setArticleCount(count: any): void {
        this.articleCountSubject.next(count);
    }
    getArticleCount(): Observable<any> {
        return this.articleCountSubject.asObservable();
    }
}

// myPage.ts:

constructor(private sharedDataService: SharedDataService){}
ngOnInit() {
    this.sharedDataService.getArticleCount().subscribe(count=> {
        this.offlineArticlesCount = count;
    });
}

// myPage.html:

<picks *ngFor="let pick of pickData" [data]="pick"></picks>
<p> {{offlineArticlesCount }} </p>

// download-offline-article.ts:

//...
this.getAllMyPurchasedOfflineArticles().subscribe((res: any) => {
    this.sharedDataService.setArticleCount(res.count);
},
//...

Answer №4

Utilize the template reference variable method:

<picks *ngFor="let pick of pickData" [data]="pick"></picks>
<p>{{ offlineArticle.offlineArticlesCount }}</p>
<download-offline-article #offlineArticle [data]="data" (onDownloadOfflineArticle)="downloadOfflineArticle($event)"></download-offline-article>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a TypeScript rule called "no-function-constructor-with-string-args" that needs an example?

The description provided at this link is concise: Avoid using the Function constructor with a string argument to define the function body This might also apply to the rule missing-optional-annotation: A parameter that comes after one or more optiona ...

Problem with Angular app not loading in IE 11 due to ES6 targeting

I have encountered an issue while developing a new application with IE11 as the target browser. When I set the target to es6, the app fails to load and displays the error shown below. https://i.stack.imgur.com/FL8BG.png However, when I switch the target ...

Failed connection between Angular and Firebase for push notifications

I have integrated a firebase Service worker into my Angular app to receive cloud messages from Firebase Cloud Messaging. However, I am facing an issue where, when the notification is received while the app is running in the background and I click on it, th ...

Tips for switching between two icons within the same div by clicking on the icon

I am looking to implement a feature in angular2 that is similar to marking an email as Starred. For example, when I click on the empty star icon, it will make some service calls to check if the item should be starred. If the result is true, then a new icon ...

View the Sub content from a ngFor Array upon clicking

For my project, I have a scenario where each card value is displayed on the screen by looping over JSON data using ngFor. The objective is to show specific information from the JSON when a user clicks on a card, utilizing *ngIf to display content only in a ...

Mat-SideNav in Angular Material is not toggled by default

<mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>{{applicationN ...

Standardize API response using NgRX Entity

Can the NgRx Entity library normalize a nested JSON api response? If I have data structured like this: [ { "id": "1", "title": "My first post!", "author": { "id": "123", "name": "Paul" }, ...

Is it possible to utilize components or directives in both AngularJS and Angular when developing a hybrid application?

Is it possible to use AngularJS directives/services that have been "upgraded" in a hybrid app created with ngUpgrade for migrating from AngularJS to Angular? Can Angular components that are "downgraded" still be used on the Angular side as well? While res ...

Encountering errors in Typescript build due to issues in the node_modules directory

While running a typescript build, I encountered errors in the node_modules folder. Despite having it listed in the exclude section of my tsconfig.json file, the errors persist. What's puzzling is that another project with identical gulpfile.js, tsconf ...

The sequence for initializing properties in Typescript

In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init, and class B overrides the init function. a.ts export default class A { constructor() { this.ini ...

Is it advisable to specify data types for my JSON data in TypeScript?

For the shopping application in my project, I am utilizing a JSON structure to categorize products as either hot or branded. However, I encountered an issue when trying to define a type for the entire JSON object labeled "full". Despite my attempts, it app ...

An object may be null when its type is A or undefined, but we are certain it is not undefined

Since the release of version 4.8.4, the TypeScript compiler has been flagging an issue with the following code: type A = {v: number} function get_the_first<T>(xs: T[]): T | undefined { if (xs.length > 1) return xs[0]; else ...

Choosing a personalized component using document selector

Currently, I am working on an application using Stenciljs and have created a custom element like this: <custom-alert alertType="warning" alertId="warningMessage" hide>Be warned</custom-alert> The challenge arises when attem ...

When utilizing the Emulator in Firestore rules, request.auth will be null

I have been experimenting with testing Firestore rules using AngularFire and Firebase Emulators. My firestore rule is quite simple, only checking if the user is logged in or not. The issue arises when no user can access the Firestore, even though they ...

There was a problem encountered while parsing the module due to an unexpected token. It appears that this file type requires a specific loader in order to be properly handled

I am currently experimenting with the Angular map API to track a location in a search box field within Ionic 3. I am encountering an issue that says "Uncaught (in promise): Error: Module parse failed: Unexpected token (91:0). You may need an appropriate l ...

Guide on utilizing async/await in .ts files (Encountering error message: "async functions can only be used when targeting ECMAScript 6 or above")

Initially, my project consisted of only app.js using ExpressJS as the main file with numerous lines of code. My development manager instructed me to refactor the code and move some functions into a separate .ts file (transition from JavaScript to TypeScrip ...

Semantic HTML in Angular

Having a React background, I'm used to custom components rendering as expected without any extra wrapper tags. However, in the case of Angular, I've noticed that my custom component my-custom-component adds an additional tag around the content. & ...

What is the best way to specify a function parameter as a Function type in TypeScript?

I'm currently delving into the world of TypeScript and I am unsure about how to specify a function parameter as a function type. For instance, in this piece of code, I am passing a setState function through props to a child component. const SelectCity ...

What is the best way to organize a collection of objects by a specific characteristic in Typescript?

Imagine you have an array of objects with the following structure: type Obj = { id: number, created: Date, title: string } How can you effectively sort this array based on a specific property without encountering any issues in the type system? For ...

Vue/Vite vanilla setup encountering a 'Failed to fetch dynamically imported module' TypeError

We're currently working with a vanilla Vue/Vite setup and I'm encountering the error message TypeError: Failed to fetch dynamically imported module in Sentry logs. It appears that these errors coincide with new deployments to production, but I d ...