The journey of communication: uncovering the essence of @input between parent and

I'm diving into Angular and currently working on the @Input phase.

Within my main app, there's a child component. Inside app.component.ts, I've declared a test variable that I wish to pass from app.component.ts to child.component.ts.

// app.component.ts:
export class AppComponent {
    test = 10;
}  

// child.component.ts:
export class ChildComponent {
    @Input() fromParent: number;
    childVar = fromParent + 5;

    show() {
        console.log(this.childVar);
    } //this should to show 15 in console...
}

So, how exactly can I achieve this? Any suggestions?

Answer №1

Here is a simple example demonstrating how a parent component can bind properties for a child component to access.

Parent component template: parent.component.html

<child-component 
    [fromParent]="fromParent">
</child-component>

Parent component class: parent.component.ts

export class ParentComponent {
  fromParent: string = 'String from parent';
}

Child component class: child.component.ts

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

//...

export class ChildComponent {
  @Input() fromParent: string;
}

Child component template: child.component.html

String from parent: {{ fromParent }}

Answer №2

Within the app.component.html file, you invoke the child component's selector (assuming it is named child-app):

<child-app></child-app>

Next, include the property declared as @input() and bind it to the value within the AppComponent (which in this case is test):

<child-app [fromParent]="test" ></child-app>

Lastly, it is recommended to restructure your code snippet as follows:

****child.component.ts:****

export class ChildComponent { // This is not AppComponent
    @Input() fromParent: number;
    childVar: number;


    show() {
        this.childVar = this.fromParent + 5; // This operation should be placed inside a method 
        console.log(this.childVar);
    } // The expected output in the console should be 15...
}

Answer №3

In Angular, property binding and event binding are fundamental concepts.

Simply put, components define custom elements while directives define custom attributes. For example, h1 is a predefined HTML tag, but app-root is not. Therefore, in Angular, components create custom elements and directives create custom attributes.

An attribute or tag becomes a child of another when it is used inside the component html of the parent tag.

A child component can send data to its parent using event binding.

Conversely, a parent component can pass data to its child through property binding.

To indicate that a variable inside a child component can be accessed by the child template, we use the @Input() decorator on the property.

Answer №4

To assign the property to the child selector within your app.component.html, do the following -

<!-- replace element selector with yours -->
<app-child [fromParent]="test"></app-child>

Additionally, you can choose to implement the OnChanges interface in your child.component.ts. This will look like this -

export class ChildComponent implements OnChanges {
    @Input() fromParent: number;
    childVar = fromParent + 5;

    ngOnChanges() { // automatically called when updated by parent.
        console.log(this.childVar);
    }

    show() { // called when needed
        console.log(this.childVar);
    }
}

Answer №5

Each time you add a child component, you are setting up its variable. For example, within the parent's template, you would include the following:

<app-child [fromParent]="test"></app-child>

Answer №6

*Imagine a scenario where the apples component remains constant across instances, but we require a unique description for each one. Input comes to our rescue.*  

  // app.component.html
<app-apple [description]="appleDescription"></app-apple>

Any property within app.component.html can serve as appleDescription.

// apple.component.ts
import { Component, OnInit, Input } from '@angular/core';
...
export class AppleComponent implements OnInit {
   @Input() description: string;
...

The parent component, in this case app.component.html, passes on the description. The [description] attribute accepts any value, making it accessible throughout apple.component.html or apple.component.ts like any other regular class property with standard change detection mechanism applied.

// apple.component.html
{{ description || 'No input provided yet...' }}

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

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

How can I set up a KeyboardEvent listener in JavaScript?

My attempt to use @keydown resulted in an error: Type 'Event | KeyboardEvent' is not assignable to type 'KeyboardEvent'. Type 'Event' is missing the following properties from type 'KeyboardEvent': altKey, c ...

Arrange information in table format using Angular Material

I have successfully set up a component in Angular and Material. The data I need is accessible through the BitBucket status API: However, I am facing an issue with enabling column sorting for all 3 columns using default settings. Any help or guidance on th ...

Tips for effectively handling projects that call for varying versions of TypeScript within Visual Studio

In some cases, developers have had to downgrade their TypeScript version in order for it to work with a specific npm package version. Is it possible to do this with Visual Studio? I recently obtained a sample solution that utilized the angular2 npm packag ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

Typescript: Retrieve an interface containing properties that are found in interface A, but not in interface B

I am currently developing a mapper that will facilitate the translation between a serialized entity state and a form state. In the context of two given interfaces A and B, I am exploring ways to derive a third interface C that includes properties present ...

Syncing a line's position with the cursor in Angular using the ChartJs Annotation Plugin

I've been working on creating a crosshair using the annotation plugin, and while I've been able to modify the line's value, it doesn't seem to update on the chart. Here are the details of my chart options : public financialChartOptions ...

Angular 7 navigation successfully updates the URL, but fails to load the corresponding component

Despite exhausting all other options, I am still facing a persistent issue: when trying to navigate to a different component, the URL changes but the destination component fails to load. Explanation: Upon entering the App, the user is directed to either ...

Implementing Angular's Advanced Filtering Across Multiple Data Fields

I am looking to create a custom filter for a list. Here is an example of the Array of Objects: myList: [ { "id": 1, "title":"title", "city":"city name", "types":[ { ...

Troubleshooting: Dealing with Cross-Origin Resource Sharing (CORS)

I'm facing an issue with my server.js files. One of them is located inside the backend folder, and when I run nodemon server.js on localhost:3000, everything runs smoothly. I start Angular by running ng serve inside the angular folder, and logging int ...

How to refresh a specific component or page in Angular without causing the entire page to reload

Is there a way to make the selected file visible without having to reload the entire page? I want to find a cleaner method for displaying the uploaded document. public onFileSelected(event): void { console.log(this.fileId) const file = event.targe ...

Guide on incorporating a YouTube iframe in React with Typescript

It appears that Typescript is posing some challenges for me in this scenario. Here's the code snippet I am trying to include: <iframe width="560" height="315" src="https://www.youtube.com/embed/BLAH?showinfo=0" frameBorder="0" ...

Updates made to Angular components do not get transpiled to JavaScript

Embarking on my first ASP.NET Core application journey with Angular 2! User access is a top priority for the application. Facing the absence of an Angular template in Visual Studio 2017, I opted to use Powershell and Yoman to generate an Angular project s ...

Restrict the frequency of requests per minute using Supertest

We are utilizing supertest with Typescript to conduct API testing. For certain endpoints such as user registration and password modification, an email address is required for confirmation (containing user confirm token or reset password token). To facilit ...

various positions for ngb properties

My input field has both a tooltip and a dropdown attached to it using the ngb attributes: <input placement="right" ngbTooltip="Search" [ngbTypeahead]="search" /> The issue I'm facing is that I want the tooltip to appear on the right ...

Encountering the error "Unable to access the 'user' property of an undefined object when working with Angular and Firebase

Exploring Firebase for the first time while attempting to configure email and Google authentication in an Angular (v5) application. While following a tutorial (), I encounter an error: ERROR TypeError: Cannot read property 'user' of undefined T ...

The correct way to add to a string array that has been passed as props to a functional component

There is a parent component that establishes a useState hook with a string array. Then, there is a child component tasked with updating the string array. To accomplish this, both the string array and the useState function are passed to the child component. ...

Having trouble accessing undefined properties? Facing issues with the latest Angular version?

Why am I encountering an error and what steps can be taken to resolve it? Currently using the latest version of Angular. ERROR TypeError: Cannot read properties of undefined (reading 'id') Here is the JSON data: { "settings": [ { ...

What could be causing the issue with Vite build and npm serve not functioning together?

After shifting from CRA to VITE, I am encountering a problem with serving my app. I successfully build my app using vite build. and can serve it using Vite serve without any issues. However, I want to use npm's serve command. Whenever I run vite bui ...

Is there support for TypeScript in express-openid-connect?

Is there any documentation available for using express-openid-connect with TypeScript, or if it is supported at all? ...