一、 父组件给子组件传值-@input

例如 根组件是

home是父组件

header是子组件

在home.component.html引入子组件:<header

1. 父组件调用子组件的时候传入数据

<app-header [msg]="msg"></app-header>

在父组件中定义数据

public msg:string="首页组件的标题"

 

2. 子组件引入 Input 模块

header.component.ts引入:

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

3. 中 子组件中 @Input 接收父组件传过来的数据

export class HeaderComponent implements OnInit {

//接受父组件传来的数据
@Input() msg:string

 

4. 子组件中使用父组件的数据

header.component.html:

<h2>这是头部组件--{{msg}}</h2>

二、 子组件通过@Output 触发父组件的方

(1)在父组件home.component.ts中定义方法

例如

run(){

alert"我是父组件的run方法")

}

 

(2)在父组件中home.component.html中引入子组件

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

(3)在子组件header.component.ts

@input() run:any

 

 把父组件整个实例传给子组件,子组件可以调用父组件的数据和方法

 

1.在父组件中home.component.html中引入子组件

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

【home】中home为自定义

2.在子组件header.component.ts

@Input() home:any;

 

 

三、 父组件通过@ViewChild 主动获取子组
件的数据和方法

例如

父组件:new

子组件:footer

1.在父组件中new.component.html中引入子组件

定义子组件名称

<app-footer  #footer></app-footer>

2.子组件footer.component.ts定义数据和方法

 3.父组件中html中

<button (click)='getchildMSg()'>获取子组件的msg</button>

<button (click)='getchildrun()'>执行子组件的run</button>

4.在父组件ts中,引入ViewChild,button中的定义方法

 非父子组件之间传值和共享方法

1.服务可以实现

2.Loclstorage

 

posted on 2020-05-24 17:23  foremost  阅读(1606)  评论(0编辑  收藏  举报