Accessing parent variables from child components in Angular can be accomplished by utilizing input

I am working with four components and I have a need to pass data from a parent component to a child component. The structure defined within the map.html template is as follows:

<map-builder [width]="width">
    <layer [name]="'markerLayer'">        
        <marker [lat]="8.5" [lng]="55.5"></marker>
        <marker [lat]="54" [lng]="8.5"></marker>
    </layer>
    <layer [name]="'heatmapLayer'">
        <heatmap></heatmap>
    </layer>
</map-builder>

Within the LayerComponent, I have initialized variables named layer and source. In the ngOnInit() function, I have set values to both of these variables. However, I am facing challenges in accessing these values within the nested components (Marker and Heatmap). I attempted to inject the LayerComponent in the constructor(), but unfortunately, I am unable to access its variables.

Your guidance on this matter would be greatly appreciated!

Answer №1

implement the Input Decorator and ensure that the properties layer and source are made public within the LayerComponent:

export class MarkerComponent implements OnInit {
    @Input() layer;
    @Input() source;
}

export class HeatMapComponent implements OnInit {
    @Input() layer;
    @Input() source;
}

html :

<map-builder [width]="width">
<layer #lyr [name]="'markerLayer'">        
    <marker [layer]="lyr.layer" [scoure]="lyr.source" [lat]="8.5" [lng]="55.5"></marker>
    <marker [layer]="lyr.layer" [scoure]="lyr.source" [lat]="54" [lng]="8.5"></marker>
</layer>
<layer #lyr2 [name]="'heatmapLayer'">
    <heatmap [layer]="lyr2.layer" [scoure]="lyr2.source" ></heatmap>
</layer>
</map-builder>

Alternatively, inject the parent into the child's constructor:

export class HeatMapComponent implements OnInit {
  constructor(private layer : LayerComponent){}

 ngOnInit(){
    //this.layer.source
    //this.layer.layer
   this.layer.onDataChange.subscribe((data)=>{
     console.log(data.layer,data.source)
   })
 }

within your layer Component

export class LayerComponent implements OnInit {
layer: any;
source: any;
@Output() onDataChange: EventEmitter<any> = new EventEmitter<any>();

someMethod() {
    // when you change the value emit them 
    this.layer = someValue;
    this.source = someValue;

    this.onDataChange.emit({ layer: this.layer, source: this.source })
}

the reason for receiving undefined values is due to attempting to access them prior to initialization

Check out the Demo

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

What could be the reason for document.body.style.backgroundColor not working properly?

I am currently experimenting with a logic that triggers the screen to turn black upon pressing the print screen key. Despite changing the background color, it is not functioning as expected. The console has detected a change in value. What could be going ...

Set up the user django with standard configuration values

I'm currently working with Django and Angular 2, trying to create a user with default values, but it's not happening as expected... Model class Settings(models.Model): user = models.ForeignKey('auth.User', related_name='setti ...

Guide on setting a client-side cookie in NextJS 14

I attempted to store a cookie in the client's browser using Nextjs 14 app router within the API folder, but unfortunately, it did not function as expected Below is the provided code snippet: app/api/auth/login/route.js const { NextResponse } = requi ...

Converting a UUID from a string to an integer in JavaScript

Need help passing a UUID to a function that calls an endpoint to delete a blog. The UUID is in string format like "9ba354d1-2d4c-4265-aee1-54877f22312e" and I'm encountering a TypeError: Cannot create property 'message' on string '9ba35 ...

What is the best way to reset react-id-swiper every time an event handler is triggered in a React application?

I have incorporated the react-id-swiper module into my React project to create a dynamic image slider. By setting onClick event handlers on buttons with different id attributes, I trigger API calls that update the state and populate the ImageSlider compone ...

There seems to be an issue with executing an imported function from a .ts file within a TSX file in NextJs, resulting

I've encountered an issue that seems to be related to using NextJs with TypeScript. For example: // /pages/index.tsx import _ from 'lodash' export const MyComponent = () => { return ( <ul> { _.map(someArray, ...

navigating through a JSON object containing various nested elements using JavaScript

My goal is to iterate through a Json object structured like this [ { "yang_type": "container", "name": "c1", "value": "", "children": [ { "yang_type": "", "name": "type", ...

What could be causing the vue-property-decorator @Emit to malfunction in my Vue TypeScript file?

I am currently working with Typescript and Vuejs, where I have a child component called child.component.tsx import Vue from 'vue'; import Component from 'vue-class-component'; import { Emit } from 'vue-property-decorator'; ...

The type is lacking the property onAuxClickCapture and onAuxClick

When utilizing forwardRef from React, an unexpected type error occurs: The type '{ children: ReactNode; }' is lacking the properties specified in 'Pick<ILinkProps, "className" | "children" | "accept" | "acceptCharset" | "action" | ... 34 ...

Searching with Neo4j, Java and the Angular library for accurate

When my web application is opened, it displays a form where users can input a list of comma-separated usernames. The application then queries the neo4j database to fetch information for each username. I am interested in implementing autocomplete functiona ...

Retrieve data from one array using information from another array. Alternatively, merging the arrays could also be a solution

Welcome, developers, hackers, and watchers! I'm facing an issue that I can't quite wrap my head around, specifically the part where I need to extract data from one array based on another. Would merging them help? Let's take a look at the ...

Arrange JSON objects within an array based on the values of three specific fields

Within an array, I am working with the following structure: [ { "playerName": "Stack", "leaguePoints": 100, "wins": 280, "miniSeries": { "progress": "WNN", "losses": 0, "wins": 1 ...

Navigating rows in a Kendo Grid using buttons (Starting, Previous, Next, Ending)

Looking for help with navigating rows on a Kendo-Grid. I have four Buttons - First, Previous, Next, and Last. The goal is to highlight the selected record on the grid when a button is clicked. However, I'm struggling with making the Kendo-Grid highlig ...

Conceal the <p> tag if the content inside is either "0" or blank

I'm currently working on a basic calculator project and I've hit a roadblock. I need to hide certain elements based on conditions. The code snippet with explanations is provided below. function calculateArea() { var length = document.getElem ...

A guide on transferring radio button values to another program and saving them into a database with the help of PHP and jQuery

I have encountered an issue with storing radio button values in a database. Specifically, I want to assign the value of 1 for "Yes" and 0 for "No". To accomplish this, I am utilizing two scripts - a.php and b.php. The former obtains the radio button values ...

Mastering the art of utilizing Angular Material's custom-palette colors for maximum impact. Unle

I have implemented a custom material-color palette where I defined the primary and accent palettes with specific shades as shown below: $my-app-primary: mat-palette($md-lightprimary ,500,900,A700 ); $my-app-accent: mat-palette($md-lightaccent, 500,900 ...

What are the steps to achieve full screen mode in Google Chrome within an Angular 4 Application?

I'm working on an application and I'm looking to incorporate a feature where, when a user navigates from one component to another, the new component's ngOnInit method triggers the Chrome browser to enter full screen mode, similar to pressing ...

DiscordJS: updating specific segment of JSON object

I am currently working on a Discord bot using discord.JS that involves creating a JSON database with specific values. I'm wondering how I can modify the code to edit a particular object within the JSON instead of completely replacing it. if (message.c ...

Utilize a selector within a component to transfer content using content projection in Angular version 12 and above

Could anyone advise on how to load a selector from one component and pass content into it from another component in Angular? I'm still learning Angular and would appreciate any guidance or concepts you can provide. Thank you! ...

Enhancing JavaScript smooth scroll functionality

Currently, I have a functioning code that allows for smooth scrolling to an anchor point on a web page. $('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'h ...