angular 学习笔记之父子组件传值@Input @Output @ViewChild
Posted on 2019-07-01 18:49 colson.zhao 阅读(448) 评论(0) 收藏 举报style.css全局的css.(单纯写在这 和本次无关)
别人写的:https://segmentfault.com/a/1190000007890167
一、 父组件给子组件传值 -@Input
1. 父组件调用子组件的时候传入数据(news.html)
<app-header [msg]="msg"></app-header>
2. 子组件引入Input模块(header.ts文件)
import { Component, OnInit ,Input } from '@angular/core';
3. 子组件中 @Input接收父组件传过来的数据
export class HeaderComponent implements OnInit { @Input() msg:string constructor() { } ngOnInit() { } }
4. 子组件中使用父组件的数据(header.html)
<h2>这是头部组件--{{msg}}</h2>
二、 父子组件传值的方式让子组件执行父组件的方法
1. 父组件定义方法
run(){ alert('这是父组件的run 方法'); }
2.调用子组件传入当前方法
<app-header [msg]="msg" [run]="run"></app-header>
3. 子组件接收父组件传过来的方法
import { Component, OnInit ,Input } from '@angular/core'; @Input() run:any; export class HeaderComponent implements OnInit { @Input() msg:string @Input() run:any; constructor() { } }
4. 子组件使用父组件的方法。
export class HeaderComponent implements OnInit { @Input() msg:string; @Input() run:any; constructor() { } ngOnInit() { this.run(); /*子组件调用父组件的run方法*/ } }
五、 父组件通过局部变量获取子组件的引用,通过ViewChild主动获取子组件的数据和方法
1.调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer>
2. 引入ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
3. ViewChild和刚才的子组件关联起来
@ViewChild('footerChild') footer;
4.调用子组件
run(){ this.footer.footerRun(); }