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

Ways to access the types of function parameters

Obtaining a method's parameter types using ReflectAPI is simple: Reflect.getMetadata('design:paramtypes', target, propertyKey); However, the challenge arises when trying to retrieve a function's parameter types as it constantly return ...

Implicated Generic in TypeScript

Is there a way to simplify my class A implementation? export class A<TB extends B<TC>, TC> implements TD<TB, TC> { make(): TC {} } Currently, I have to specify the TC type every time I create an instance of A: class CTest {} class BTes ...

Extracting values from an *ngFor loop in Angular 8 - Here's how to do

Currently, I am utilizing *ngFor to display some data. I have a requirement to extract a specific value from *ngFor and display it in, for instance, my heading. However, when I attempted to use {{ project }}, it consistently returned undefined. Despite hav ...

Tips for simulating mouse events in Jasmine tests for Angular 2 or 4

New to Jasmine testing, I'm exploring how to test a directive that handles mouse events such as mouse down, up, and move. My main query is regarding passing mouse coordinates from the Jasmine spec to my directive in order to simulate the mouse events ...

Sharing functions between Angular components

Check out my problem statement: https://stackblitz.com/edit/angular-jk8dsj I'm facing two challenges with this assignment: I need to dynamically add elements in the app.component when clicking a button in the key-value.component. I've tried ...

Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maint ...

Error: The variable "redirectTo" has not been declared. This error can be found in the

I recently embarked on my journey to learn Angular2. I diligently followed the documentation and watched some helpful YouTube tutorials to guide me through the process. However, I've hit a roadblock while trying to configure the routes in my project. ...

Checking to see if a string meets the criteria of being a valid ARGB value

How do I verify that a string represents a valid ARGB value, such as #ffffffff for ARGB 255,255,255,255? Is there a way to validate this using TypeScript and C#? ...

Building a personalized React component poses challenges when working with MUI REACT interfaces

I am looking to develop a unique component that will display two different elements, an icon, and a title. However, I seem to be encountering errors from TypeScript regarding the declaration of my interface. The error message reads: Property 'map&apos ...

Typescript: Ways to fix the error 'rxjs/Rx does not have any exported member 'SubscriptionLike'

I'm attempting to replicate the steps outlined in this tutorial found here https://www.youtube.com/watch?v=gxCu5TEmxXE. However, upon running tsc -p, I encounter an error. Is there a specific import that I am missing? ERROR: node_modules/@angular/co ...

Verify the completeness of data types within an array in typescript

I am currently developing a comprehensive match function that I want to ensure is exhaustive during compile time. Although adding a default case would help with this, I am intrigued by some interesting dependent typing techniques I have come across. It wou ...

Using path aliases in a Typescript project with Typescript + Jest is not a viable option

Note I am able to use aliases in my TypeScript file. Unfortunately, I cannot use aliases in my test files (*.test.ts). My Configuration 1. Jest.config.ts import type { Config } from '@jest/types'; const config: Config.InitialOptions = { ve ...

Is Webpack CLI causing issues when trying to run it on a .ts file without giving any error

I am facing an issue with my webpack.config.js file that has a default entrypoint specified. Here is the snippet of the configuration: module.exports = { entry: { main: path.resolve('./src/main.ts'), }, module: { rules: [ { ...

Building an AngularJS Service with TypeScript that is Non-Singleton: A Step-by-Step Guide

I need help converting an AngularJS Typescript Service into a Non-Singleton. Can anyone provide guidance on how to achieve this? (Note: This is not the same as other questions that focus on achieving this in JS) I have included some simple pseudo code be ...

Using ngrx store select subscribe exclusively for designated actions

Is it possible to filter a store.select subscription by actions, similar to how we do with Effects? Here is an example of the code in question: this.store .select(mySelector) .subscribe(obj => { //FILTER SUBSCRIPTION BY ACTION this.object = ob ...

Trigger the Material UI DatePicker to open upon clicking the input field

I have a component that is not receiving the onClick event. I understand that I need to pass a prop with open as a boolean value, but I'm struggling to find a way to trigger it when clicking on MuiDatePicker. Here is an image to show where I want to ...

Using ReactiveForms to create templates that dynamically generate recursive structures

Describing an issue I'm facing. View Example Online I have a unique JSON that needs to be transformed into a form. To achieve this, I utilized reactive forms and iterated through the JSON properties to generate either a FormGroup or FormControl like ...

Prevent automatic submission of forms when selecting attributes in HTML forms using AngularJS

I need to create a form where users can select their branch of study. Here is the form I have designed- <form method="post" [formGroup]="formData" (click)="dataSubmit()" > <div class="form-group"> <label for="branch">Selec ...

Why isn't the table in the select query updating after an insert query is executed in Express?

Seeking assistance! Currently, I am delving into express and typescript. I have encountered an issue where the table from a select query does not update after an insert query when rendering a view. Strangely, the data in the table remains unchanged (showin ...

"Upon invoking the services provider in Ionic 2, an unexpected undefined value was

I encountered an issue while setting a value in the constructor of my page's constructor class. I made a call to the provider to fetch data. Within the service call, I was able to retrieve the data successfully. However, when I tried to access my vari ...