Passing null values between components using @Input()

One component is sending values to another:

paquete-detalle.component.ts

nombre: string;
precio: number;

ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
  this.fs.getPaqueteObject(id).valueChanges().subscribe(paquete => {
    this.nombre = paquete.nombre;
    this.precio = paquete.precio;
  });
}

paquete-detalle.component.html

{{nombre}} {{precio}} //Values are printed correctly here.
<app-reserva [precio]="precio" [nombre]="nombre"></app-reserva>

Next, in reserva.component.ts:

@Input() precio: number;
@Input() nombre: string;

constructor( private fs: FirebaseService, private fb: FormBuilder, ) {
    this.forma = fb.group ({
      nombre: [ this.nombre ],
      precio: [ this.precio ],
    });
   }

ngOnInit() {
    console.log(this.precio, this.nombre);
  }

While trying to save the values in a reactive form, I am getting null (undefined in the console) for this.price and this.name.

However, in reserva.component.html, the values are displayed as expected:

 <div class="text-center">
    <h4>{{nombre}}</h4>
    <p>From: USD {{precio}} / person</p>
 </div>

What is the correct method to pass values between components?

Answer №1

It's important to ensure that your component initialization logic is placed within the ngOnInit() method. In cases where your parent component contains asynchronous operations in its own ngOnInit(), you should delay the creation of your app-reserva component until all necessary data is available.

paquete-detail.component.ts

name: string = null;
price: number = null;

ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
  this.fs.extractPackageInfo(id).valueChanges().subscribe(package => {
    this.name = package.name;
    this.price = package.price;
  });
}

paquete-detail.component.html

{{name}} {{price}} //Ensure these values are printed correctly.
<app-reserva *ngIf="price && name" [price]="price" [name]="name"></app-reserva>    

reservation.component.ts

@Input() price: number;
@Input() name: string;

constructor( private fs: FirebaseService, private fb: FormBuilder, ) {
}

ngOnInit() {
  this.form = fb.group ({
    name: [ this.name ],
    price: [ this.price ],
  });
  console.log(this.price, this.name);
}

This answer offers a detailed explanation on the distinction between constructor and ngOnInit.

If your child component initializes an empty form, it may be due to the fact that the child component was created before the parent component completed the callback in

this.fs.extractPackageInfo(id).valueChanges().subscribe()
. By following this approach, your reservation.component.ts will not render until the parent component has fetched all the necessary data for the child.

In addition to this method, you can explore using OnChanges to have your child component respond to changes in @Input() properties or utilize Resolvers to fetch data for the route before loading the component.

Answer №2

The Input() values cannot be accessed within the constructor until they have been passed to the child component. Try constructing your form inside the ngOnInit() lifecycle hook and everything should work smoothly!

Answer №3

Code Playground - https://stackblitz.com/edit/angular-9d3bu4-so-56527061

Ensure that the parent component has specified the values for price and name when using

<app-reservation [price]="price" [name]="name"></app-reservation>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  price = 24.50;
  name = "boots"
}

app.component.html

<app-reserva [precio]="precio" [nombre]="nombre"></app-reserva>

Answer №4

Make sure to eliminate the brackets from the component and opt for using the double curly brace interpolation syntax {{ }}:

<app-reserva precio="{{precio}}" nombre="{{nombre}}"></app-reserva>

Visit this link for more information.

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

Angular HTTP post call is failing to redirect to the correct URL

https://i.sstatic.net/CzSuQ.pngCan someone assist me in resolving the http post problem? I am facing an issue where the url validation is not working correctly. Even when localhost:8084 is up and running, the error section is triggered, and the same happen ...

The classification of a property is determined by the types of the other properties present

I am trying to figure out a way in Typescript to create a general component that takes a prop called component, with the remaining props being specific to that component. How can I achieve this? For example: <FormField component={Input} ... /> Thi ...

Simplify the cognitive load of the function

I'm facing a challenge with a function that has a cognitive complexity of 24, however, we have a requirement to limit it to a maximum of 15. export function parameterValueParser<T extends Structure>( structure: T ): (parameterValue: Value) =&g ...

Clicking on the mat-icon-button with the matSuffix in the password field will always trigger a

Seeking assistance with implementing mat-icon-button matSuffix in Angular for a login page. This is my first time working with Angular and I am facing an issue with the password field. I have used mat-icon-button matSuffix, but whenever I click on the ico ...

Updating Radio Button Value in React Using TypeScript Event Handler

Whenever I try to save different values to the state, I encounter an issue where selecting female results in the male radio button being selected, and vice versa. Do you think it would be better to use a generic 'gender' variable in the state in ...

Leverage Angular, NodeJS, and Sequelize to extract data from HTML tables

Is there a way to extract data from a specific HTML table, identified by its ID, and save it into a mysql database using a NodeJS API with sequelize? The HTML code snippet that needs to be parsed: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 T ...

Expanding generic properties in React Native

Apologies if the title is confusing. I am struggling to come up with a suitable heading. I have two classes. ****************Form.tsx interface Props{} interface State{} class Form extends Component<Props, State>{ protected submit(){ // in ...

Contrasting the provision of ComponentStore directly versus utilizing provideComponentStore in Angular standalone components

As I delve into the realm of standalone Angular components and tinker with the NgRx Component Store, I find myself grappling with a dilemma on how to properly inject the component store into my component. Here's the current approach I've been usi ...

Double loading of functions on tab pages

In the work page of my application, I have created a function that is part of one of the tab's pages. This function is designed to be loaded when the page requests data from an API. It should be noted that apart from the tab's pages, the push op ...

Sending detailed exception information from asp.net core to the client (such as Angular)

Trying to retrieve exception text from the backend (ASP.NET Core) in an Angular application has been a challenge. Examples have shown the controller action's return type as either JsonResult or ActionResult. In such cases, we can utilize the followi ...

How can I hide the title bar on screens in expo?

As a newcomer to the world of react-native, I rely on YouTube tutorials to assist me in creating projects. Currently, I am working on developing an expo ui-app, however, each screen I create displays a title at the top, such as this example: https://i.ssta ...

The TypeScript declarations for Forge Viewer do not include typings related to Profiles

I've been utilizing typescript definitions for Forge from the DefinitelyTyped repository: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/forge-viewer However, there seems to be a lack of typings, particularly those associated wi ...

Experiencing a type error within Redux in a React Native project utilizing TypeScript

I am currently working on implementing a feature to store the boolean value of whether a phone number is verified or not. Within my login component: await dispatch(setOTPVerified(data.is_phone_verified)); Action.tsx: export const OTP_VERIFIED = 'OTP ...

React router loader is not functioning correctly when trying to fetch data

My attempt to fetch an array of data from an API is resulting in an empty response within the application. However, when I try the same call in a swagger, it returns the correct array. HomePage.tsx: const HomePage = () => { const books = useLoaderDat ...

Type of Request: POST Error Code: 400 Unacceptable Request Referrer Directive: strict-origin-when-cross-origin

import { Restaurant } from "@/types" import { useAuth0 } from "@auth0/auth0-react" import { useMutation } from "@tanstack/react-query" import { toast } from "sonner" const API_BASE_URL = import.meta.env.VITE_API_BAS ...

Is there a way to accurately capture the timestamp of when a user clicks the submit button in Angular 2 framework?

Within my HTML file, I have implemented an onRegisterSubmit() function to handle the submission of a form. The register.ts file is responsible for adding user input from the form, as well as validating and authenticating the user. onRegisterSubmit(){ ...

Pass the API_BASE_URL parameter from the Angular 7 configuration

Currently, I am developing an Angular 7 Application using es6 Javascript and Swagger integration. My current challenge involves adding the configuration to APP_INITIALIZER in the app.module file: export class SettingsProvider { private config: AppConfi ...

What is the best way to create a sortable column that is based on a nested object within data.record?

I am utilizing jquery jtable to showcase some data in a table. I have been using the following code snippet for each field in the table to display the data and enable sorting: sorting: true, display: (data) => { return data.record.<whatever_value ...

Type inference in Typescript is especially powerful when used in conjunction with decorators

I am curious as to why the compiler in Typescript cannot infer the new type of a class when decorators or annotations are used. Interestingly, if I use the traditional ES5 method (manually calling the decorator), it works without any issues. Here is an ex ...

As soon as you start typing in the TextInput field, the keyboard abruptly disappears

Whenever I attempt to input a value into my TextInput, the keyboard on mobile closes and the value does not show up in the TextField. This issue arises when I utilize the useState hook to store the input in a variable. Is there a way to resolve this behav ...