Utilizing Angular signals to facilitate data sharing among child components

I have a main component X with two sub-components Y and Z. I am experimenting with signals in Angular 17. My query is how can I pass the value of a signal from sub-component Y to sub-component Z?

I have attempted the following approach which works initially, but fails to update when the signal's value changes.

subComponentY.component.ts

 export const data = signal<any>('');

 fetchData() {

    this.loading = true;
    
    const functions = getFunctions(getApp());
    connectFunctionsEmulator(functions, 'localhost', 5001);

    const getInfo = httpsCallable(functions, 'getInformation')
    getInfo(this.url.value)
    .then( (result: any) => {
      // result.data returns an object
      data.set(result.data);
      console.log(data());
    })
  }

subComponentZ.component.ts

import { data } from '../subComponentY/subComponentY.component';

data_ = data;

subComponentZ.component.html

<p class="">{{data_().data.title}}</p>

Although the console displays the updated signal data, the HTML template does not reflect these changes. Any suggestions?

Answer №1

You have the option to utilize it as an @Input, see the functional example provided below!

parent

import { CommonModule } from '@angular/common';
import { Component, signal } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { TestComponent } from './test/test.component';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, TestComponent],
  template: `
    <app-test [item]="item"></app-test>
  `,
})
export class App {
  item = signal<any>('');

  ngOnInit() {
    this.retrieveFileInformation();
  }

  retrieveFileInformation() {
    // this.loading = true;

    // const functions = getFunctions(getApp());
    // connectFunctionsEmulator(functions, 'localhost', 5001);

    // const getInfo = httpsCallable(functions, 'getInformation')
    // getInfo(this.url.value)
    // .then( (result: any) => {
    // result.data return object
    // mock the API call!
    this.item.set({ data: { title: 'hello!' } });
    setTimeout(() => {
      this.item.set({ data: { title: 'hello world!' } });
    }, 2000);
    console.log(this.item());
    // })
  }
}

bootstrapApplication(App);

child

import { CommonModule } from '@angular/common';
import { Component, Input, OnInit, Signal } from '@angular/core';

@Component({
  selector: 'app-test',
  imports: [CommonModule],
  template: `
    <p class="">{{ item()?.data?.title | json }}</p>

  `,
  standalone: true,
})
export class TestComponent implements OnInit {
  @Input() item!: Signal<any>;
  constructor() {}

  ngOnInit() {}
}

Check out the StackBlitz demo here!

Answer №2

Avoid using @inputs for signals in your components. Signals are most powerful when used for cross-component communication, rather than just establishing parent-child relationships.

To prevent unnecessary updates and potential issues, consider creating a service to share the signal between components instead.

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

Challenges faced when integrating Angular with Bootstrap elements

I am currently in the process of developing a website using Angular 12, and although it may not be relevant, I am also incorporating SCSS into my project. One issue that I have encountered pertains to the bootstrap module, specifically with components such ...

Using styled-components and typescript to override props

Currently, I am faced with the challenge of using a component that necessitates a specific property to be set. My goal is to style this component with the required property already defined, without having to manually specify it again during rendering. Howe ...

The term "define" is not recognized when constructing a Next.js application

Currently, I am working with Next version 10.0.1 and React 17.0.2. While attempting to build my Next app, I encountered the following error: ReferenceError: define is not defined at Object.<anonymous> (/Users/username/Desktop/project/node_module ...

Avoiding loading certain images within an *ngFor loop

Is it possible to control the loading of images within an *ngFor loop in Angular? Load image with index X first Fire a function once all other images have loaded The goal is to prioritize the display of important images while optimizing bandwidth usage. ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

Struggling to implement JSS hover functionality in a project using React, Typescript, and Material UI

I am a newcomer to the world of React/Typescript/Material UI and I am trying to understand how to work with these technologies together. While researching, I came across a similar question related to using hover with Material-UI. However, the syntax was d ...

Input a value to request in the Mssql node

I am using angular2 and mssql to establish a connection with SQL Server. This is my code snippet: var express = require('express'); var app = express(); var sql = require("mssql"); // database configuration var config = { user: 'sa&ap ...

"Learn how to dynamically change the color of a button in Angular after it has been clicked

Can someone assist me in changing the button color to red after it has been clicked? I am looking for guidance on how to achieve this. The current code snippet is as follows: <td> <button mat-icon-button color="primary"> <m ...

Prepare fixtures for commands in Cypress before executing the hook

One of my main tasks is to load the fixtures file only once and ensure it is accessible across all project files. To achieve this, I created a fixtures.js file with the following content: let fixturesData; export const loadFixturesData = () => { cy ...

Tips for managing the data type of a bound value through ngModel: preventing number distortion to string

I posted a query and managed to solve it. However, I observed that even though the provided data consists of objects defined like this: export interface GisPoint { e: number; n: number; } when a user inputs a value, the original content changes from { e: ...

The menu's mouseover event is activated when hovering over the inner element

Whenever a user hovers over a specific element, a menu appears. This menu remains visible only as long as the user is hovering over it. However, the issue arises when there are elements within the menu itself, causing the menu to hide when the user hovers ...

Can you explain how NGXS store manages its data storage? Is there a memory limit set for the NGXS store? And where exactly is the NGXS store memory located within the browser

Although I attempted to learn NGRX from their official site, I found myself lacking a clear understanding of where and how the data is stored within NGRX. Additionally, I could not find any information regarding the maximum limit of data that can be stor ...

RTK update mutation: updating data efficiently without the need to refresh the page

I am facing an issue with my mui rating component in a post-rating scenario. Although the rating updates successfully in the data, the page does not refresh after a click event, and hence, the rating remains enabled. To address this, I have implemented a d ...

Tips for relocating the indicators of a react-material-ui-carousel

I am working with a carousel and dots indicators, but I want to move the indicators from the bottom to the circular position as shown in the image below. I attempted using a negative margin-top, but the indicators ended up being hidden. Is there another ...

The TypeScript compiler is indicating that the Observable HttpEvent cannot be assigned to the type Observable

Utilizing REST API in my angular application requires me to create a service class in typescript. The goal is to dynamically switch between different url endpoints and pass specific headers based on the selected environment. For instance: if the environmen ...

I am unable to link to 'dataSource' because it is not a recognized property of 'table'

After spending two days exploring all potential solutions provided (listed below), and upgrading Angular and Material from version 7 to 8, I still encounter the same issue. Unable to bind to 'dataSource' since it's not recognized as a pro ...

"Acquiring the version number in Angular 5: A step-by-step

How can I retrieve the version from my package.json file in Angular 5 project? I am using Angular-Cli: 1.6.7 and npm 5.6.0 Here is a snippet from my enviroment.ts file: export const enviroment = { VERSION: require('../package.json').versio ...

Angular - A simple way to conceal a specific row in a mat-table using Angular

I am looking to dynamically hide or show a specific column in a table by clicking on a button. The goal is to hide or delete the weight column when the "hide weight" button is clicked, and then show the weight column when the "show weight" button is clicke ...

Is there a way to adjust the opacity of a background image within a div?

I have a lineup of elements which I showcase in a grid format, here's how it appears: https://i.stack.imgur.com/JLCei.png Each element represents a part. The small pictures are essentially background-images that I dynamically set within my html. Up ...

When the button is clicked, (ngSubmit) will be triggered

In my Angular2 Form Component, I have implemented two buttons with different functionalities. Button Submit: This button submits all the values to the API. Button Add: This button adds an object to an array. Here are the two methods: onSubmit() { this. ...