Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

How to pass value of variable from one component to another component in Angular?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 45

How to pass value of variable from one component to another component in Angular?

Post by admin » Sat Aug 31, 2019 5:36 pm

src/app/app.component.ts

Code: Select all

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  
  // Define the variable in app.components.ts and
  // will use this variable in hello.component.this

  name= 'rajesh';
  

}

src/app/app.component.html

Code: Select all

<app-hello name="{{ name }}"></app-hello>
<p>
  this is a demo about how to pass variable of one component to another component in Angular. Here name variable is defined in app.component.ts and being used in hello.component.ts
</p>
src/app/hello.component.ts

Code: Select all

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

@Component({
  selector: 'app-hello',
  templateUrl: './hello.component.html',
  styleUrls: [ './hello.component.css' ]
})
export class HelloComponent  {
  @Input() name: string;
}

src/app/hello.component.html

Code: Select all

<h1>hello {{name}}</h1>
app.module.ts

Code: Select all

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

Demo - https://angular-oziwpw.stackblitz.io

Post Reply