Angular

父子组件传值@Input @Output @ViewChild

2018-05-03  本文已影响282人  faith3729

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

  1. 父组件调用子组件 的时候传入数据
<app-header [msg]="msg"></app-header>
  1. 子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
  1. 子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit { @Input() 
msg:string
constructor() { }
ngOnInit() {
}
}
  1. 子组件中使用父组 件的数据
<h2>这是头部组件--{{msg}}</h2>

二、让子组件执行父 组件的方法(父子组件传值的方式)

  1. 父组件定义方法
run(){
alert('这是父组件的 run 方法');
}

2.调用子组件 传入当前方法

<app-header [msg]="msg" [run]="run"></app-header>
  1. 子组件接收父组件 传过来的方法
import { Component, OnInit ,Input } from '@angular/core';
@Input() run:any;

export class HeaderComponent implements OnInit {
@Input() msg:string @Input() run:any;
constructor() { } }
  1. 子组件使用父组件 的方法。
export class HeaderComponent implements OnInit {
@Input() msg:string; @Input() run:any;
constructor() { } ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
} }

三、让父组件执行子组件的方法

  1. 父组件定义方法(HTML)
       <button (click)="myChild.GetTestInfo('我是父组件传过来的值')">按钮调用child2的greeting方法</button>
  1. 父组件定义方法(TS)
import {  ViewChild } from '@angular/core';

@ViewChild(***) auditorListSchedule: **;
  1. 子组件定义方法(TS)
GetTestInfo(str: string) {
alert('这是子组件的数据' + str);
}
上一篇 下一篇

猜你喜欢

热点阅读