Angular Note 4 --- Components sharing values

71 阅读1分钟

Parent to Children

Image we have two components, the first one is called "home" which is a parent component, and the second one is called "header" which is a child component.

Now if we want to pass a value from parent component to the child component, what we need to do is:

import "Input" module from @angular/core

home.component.ts

export class... {

  public title: string = "I am a title from home component";

...
}

home.component.html

<app-home [title]="title"></app-home>

Accept the value from home component

header.component.ts

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

export class ... {
  
  @Input() title: any;

... 
}

header.component.html

<div>{{title}}</div>

We can also invoke parent's function by using this method:

home.component.ts

run() {

  console.log("yes")

}

home.component.html

<app-header [run]='run' [home]='this'></app-header>

header.component.ts

@Input() run: any;

// You can use all variables and functions here
@Input() home: any;

getParentRun() {

   this.run();
   console.log(this.home.title);

}

header.component.ts

<button (click)='getParentRun()'>Click Me</button>

Children to Parent

If we want to use all functions and values in child components, we need to use @ViewChild

home.component.ts

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

@ViewChild('header') header: any;

getChildMsg() {

  console.log(this.header.msg);

}

home.component.html

<app-header #header ></app-header>

<button (click)='getChildMsg()'></button>



header.component.ts

public msg: string = "This is from child component";