Please enable Javascript for better experience...
Passing parameter from one component to another component - Angular 6
By Rahul Kumar Jha | Aug 14, 2018 | In Articles | Total Views [ 2813 ]
Taged In
(0 Like)
Rate

intial description

Introduction

Let suppose we have a parent component (AppComponent) and a child component (HeaderComponent). We want to declare a variable in AppComponent and use it in HeaderComponent. Let’s see how we will achieve this.

Step 1

Define a variable “welcomeNote” inside app.component.ts file.

App.compoment.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
//declare a variable welcomeNote having title and appName
welcomeNote = {
initial: "Welcome",
appName: "My Test App"
}
}

Step 2

In app.component.html add reference of header component selector (app-header) and input a tag “title” having welcomeNote variable. You can take any name. Best is to take variable name (welcomeNote) as a tag name.

<app-header [title] = "welcomNote"></app-header>

Step 3

In header.component.ts file include Input in @angular/core and add title variable in @Input decorator

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

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

// This decorator recieves input parameter passed from parent component
@Input() title;
constructor() { }

ngOnInit() {
}

}

Step 4

Use this variable (title) in header.component.html

<p> to </p>

Output

output

Share this

About the Author

Rahul Kumar Jha
Rahul Kumar Jha
Founder, Developer dotnet-concept.com

Public profile: user/profile/99900001


Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, ANGULAR, ANGULAR JS, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

User's Comments


 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment
 
 
 
 
 
 
Sponsors