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

一、父组件给子组件传值 -@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);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容