What is the best method for transferring data from a parent to a child component in Angular?

Is there a way to share a string variable with parent and child components in Angular (TypeScript) without the child component updating automatically when the input variable is updated? I want the child component to only update when the data is sent from the parent component. How can this be achieved?

This is the code for my parent component.html

 <div>
   <mat-form-field>
     <input matInput type="text" [(ngModel)]="city">
   </mat-form-field>
   <button mat-button (click)="getWeather()">
      <mat-icon matSuffix>search</mat-icon>
   </button>
 </div>

<app-city-weather [testCity]="city"></app-city-weather>

This is my parent component.ts

 city: string;

 getWeather() { 
// HTTP request code here
}

This is the code for my child component.html

<p> 
The child component is functioning correctly!
</p>

And this is the code for my child component.ts

@Input() testCity: string;

Answer №1

To enhance the functionality of the child component, I propose creating a dedicated class property solely for storing the city value:

// Structure.

 <div>
   <mat-form-field>
     <input matInput type="text" [(ngModel)]="city">
   </mat-form-field>
   <button mat-button (click)="getWeather()">
      <mat-icon matSuffix>search</mat-icon>
   </button>
 </div>

<app-city-weather [testCity]="cityChild"></app-city-weather>

// Logic.

city: string;
cityChild: string;


getWeather() { 
 this.cityChild = this.city;
 // Make HTTP request
}

Answer №2

1. Implementing Conditional Display with *ngIf in Angular

If you are facing issues with displaying intermediate values for city in your child component while the user is typing a city name in the parent component, and you only want to show the final city name in the child component after the user clicks on 'getWeather' button to fetch weather data, you can solve this by using a conditional check with *ngIf in your child template.

This way, the city will only be displayed in the child component when the weather data is available, eliminating the display of intermediate values for 'testCity'.

Child Component Template:

<p *ngIf="weather">{{ testCity }}</p>
<div>{{ weather }}</div>
@Input() testCity: string;
@Input() weather: string;

Parent Component Template:

<input matInput type="text" [(ngModel)]="city">
<button mat-button (click)="getWeather()">Get Weather</button>

<app-city-weather [testCity]="city" [weather]="weather"></app-city-weather>
city: string;
weather: string;

getWeather() { 
 this.weather = 'Sunny';
}

2. Using Subject to Send Data from Parent to Child as an Event

If you need to send data as an event from the parent to the child component, you can utilize a Subject in the parent component and pass it as an Observable to the child, where you can subscribe to value changes.

Child Component Template:

<p>{{ city$ | async }}</p>
@Input() city$: Observable<string>;

Parent Component Template:

If you only require the city value in the getWeather function and the child component, you can remove [(ngModel)="city"] and directly access the input value to pass to getWeather.

<input #cityInput matInput type="text">
<button mat-button (click)="getWeather(cityInput.value)">Get Weather</button>

<app-city-weather [city]="currentCity.asObservable()"></app-city-weather>
currentCity: Subject<string> = new Subject<string>();

getWeather(city: string) { 
 // Send current city to child
 this.currentCity.next(city);
}

Answer №3

One way to manage shared data in your application is by creating a service.

To do this, you can define a CityService class with a property called city.

After creating the service, it should be provided in your app.module file.

Once the service is set up, you can inject it into any component where you need access to the shared data. This is typically done in the constructor of each component.

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

Creating a dropdown menu in Bootstrap 5 without using any of the Bootstrap

In my Angular application, I have a header with icons and pictures that I would like to use as dropdown menus. The code snippet for this functionality is shown below: <li class="nav-item dropdown"> <a class="nav-li ...

Adding elements to a page while it is running can be achieved using a variety

Working on a college project, I am developing a demo web-app in Angular. The goal is to implement a feature where clicking a button adds a new node to the DOM tree. In JavaScript, a simple solution would be: document.getElementById('ticket-container& ...

React-Admin error: Attempting to invoke a built-in Promise constructor without using the new keyword is not allowed

I'm currently facing an issue where I am trying to retrieve data using a hook. Strangely, there are no TypeScript errors appearing, but when I run the code, a console error pops up stating "Uncaught TypeError: calling a builtin Promise constructor wit ...

Utilize personalized Bootstrap variables within your Angular application

I am attempting to customize the default colors of Bootstrap within my Angular project. I have established a _variables.scss file in the src directory. Within this file, I have included the following code: $primary: purple; Next, I imported my _variables ...

Discovering a method to recover information obtained through intercepting an observable

I am currently working on an Angular 6 cli application where a component utilizes a service to fetch data. As part of my project, I am incorporating an ngrx store into the application. I am considering abstracting the interactions with the store within the ...

Determining the argument data type when calling the function

const func = <T>( obj: T, attr: keyof T, arr: T[typeof attr][], ) => { } const obj = {foo: 1, bar: true}; func(obj, 'foo', [1]); func(obj, 'bar', [1]); // shouln't be ok func(obj, 'foo', [true]); // shoul ...

Transitioning Angularjs tooltips to Angular 14

I am in the process of transitioning my Web application from AngularJS 1.5.3 to Angular 14.2. One feature used in my application is a popover template, as shown below: html <a id="{{mapObj.stId}}" popover-template="'{{mapObj.statusT ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

What is the best way to organize information within a template using a *ngFor loop without needing to include functions directly in the template?

When working with Angular 11, I encountered a scenario where a Component receives an array of data from an external source that needs to be displayed in a template using a *ngFor loop with custom formatting. While my initial approach involved creating func ...

The correct way to assign a value within an Angular Observable subscribe function

Having some trouble with a basic form using @angular/material (although the material aspect shouldn't make a difference) that is structured like this: <div *ngIf="user"> <form> <mat-form-field> <m ...

Troubleshooting: Issue with implementing BehaviorSubject and async pipe in Angular component extension

While working on my code, I encountered an issue where I couldn't get the parent component's async pipe to trigger from a child component in order to update the view. To better explain this problem, let me show you a simplified version of my code ...

Error in the design of PrimeNg calendar rendering in Angular 2

I have implemented the primeNg module from primefaces in Angular 2 to create a timepicker. It seems to be working, but the design appears broken. Is there something else I need to add to correct the design? Below are the versions of the packages I used: P ...

Passing an object from an Angular application to a backend server in Node.js using the

I have a YAML file with the following structure: Layouts: - Name: Default Layout LayoutId : 1 ConfiguredSegments: LiveA : Height : 100 Id : LiveA Ref1A : ...

Navigating the coexistence of Angular 1.2 and Angular 2 for an incremental upgrade

After working on a large code base in Angular 1.2 with multiple custom directives, I decided to seek advice from experts before making any changes. While going through the Angular documentation, I was pleased to discover the UpgradeAdapter for incremental ...

Using Angular to show information in a textarea box from a service

Recently, I picked up Angular and worked on the tour-of-heroes app. Currently, I'm facing a challenge in displaying a set of steps in a textarea based on the selected hero. The idea is that when hero1 is selected, it should show step 1, and upon click ...

How to eliminate arrows in ngx-bootstrap datepicker?

I recently started working with Angular and Bootstrap and I'm facing an issue. I am using a ngx bootstrap datepicker, but I would like to remove the standard arrows on the buttons of the datepicker calendar. Here is a screenshot of the problem: https ...

Learn how to use Angular2 or TypeScript to display 'unsubscribe' and 'subscribe' text on a toggle button

I'm working on a toggle button that initially displays the word subscribe on the thumb. When the toggle is disabled, I want it to show unsubscribe instead. Can someone please help me achieve this functionality? Here's the code snippet: <md-s ...

What could be causing my NextJS application to not recognize the _document.tsx file?

Seeking assistance in understanding why my _document.tsx is not loading properly within my nextJS application. My Attempts So Far I have been diligently following the NextJS documentation for creating a custom _document.js. Despite my efforts, I am unable ...

Testing ngrx effects action failure and how it impacts the

Having issues with this particular effect login$ = createEffect(() => this.actions$.pipe( ofType(AuthActions.login), exhaustMap((action) => this.service.login(action.credentials).pipe( map((data: LoginResponseDto) =& ...

Utilizing React Typescript to Efficiently Manage Multiple Checkboxes within a List

I'm working on a scenario where I have to manage multiple checkboxes in a list Only one checkbox can be selected at a time For example, if I toggle on Checkbox 1 and then click on Checkbox 2 - I want to automatically toggle off Checkbox 1 as I toggl ...