(子组件传值给父组件经过触发方法来传值方法。首先父组件传值()给子组件,子组件接收后调用父组件传来的值(方法)时会把值传给父组件)
1.如今父组件news.component.ts里d定义一个接收子组件值的方法html
export class NewComponent implements OnInit { //在这里定义和获取要传递的值,例如: public name = '我是发哥'; run (){ alert("父组件传给子组件的run方法") } //接收子组件传值的方法(参数自定义:就是子组件传过来的值) getDataFromChild (childData) { alert(childData) } }
2.在父组件news.component.html里的子组件标签里绑定getDataFromChild方法:web
<div class="news"> <app-header [getDataFromChild]="getDataFromChild"></app-header> </div>
3.在子组件header.component.ts里接收父组件传过来的值getDataFromChild方法:app
3-1.需导入Input: import { Component, OnInit ,Input} from '@angular/core'; 3-2.经过 @Input()接收传过来的值 @Input() getDataFromChild; //getDataFromChild方法
4.在子组件header.component.ts里定义一个方法来调用传过来的父组件方法svg
export class HeaderComponent implements OnInit { //经过 @Input() 引入news父组件传过来的值 @Input() getDataFromChild; public userInfo = "这是子组件的数据"; constructor() { } ngOnInit() {} sendParent () { this.getDataFromChild(this.userInfo) } }
5.在子组件header.component.html里绑定本身的处理方法sendParent (),也能够绑定父组件的方法来传值this
<p> <button (click)="sendParent()">点我传值给父组件</button> </p> <p> <button (click)="getDataFromChild(userInfo)">点父组件传过来的方法传值给父组件</button> </p>
1.在子组件header.component.ts里引入Output,EventEmittercode
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
2.在子组件header.component.ts实例化EventEmittercomponent
export class HeaderComponent implements OnInit { // 实例化 EventEmitter对象,<string>指定变量类型,也可不指定变量类型 // @Output() private outer = new EventEmitter<string>(); @Output() toParent= new EventEmitter(); public userInfo = "这是子组件的数据"; constructor() { } ngOnInit() {} }
3.在子组件header.component.ts里经过 EventEmitter 对象 toParent实例广播数据(在这里定义一个方法)xml
resData () { // emit()里的参数就是要传递的值,toParent就是上面EventEmitter 实例化的对象名称toParent this.toParent.emit('msg fron child') }
4.在父组件news.component.html里把在定义的header.component.ts里定义的方法(带个参数$event)传给子组件header.component.ts里EventEmitte的起的实例对象监听htm
//toParents是子组件header.component.ts里EventEmitte的起的实例对象名 <app-header [title]="title" (toParent)="resData($event)"> </app-header>
5.在父组件里定义一个方法:对象
// 传个参数事件对象(用于拿子组件传过来的值) resData (e) { console.log(e);//会打印出子组件传过来的值 }
6.在子组件里写一个按钮来触发
<button (click)="resData()">经过执行子组件方法来触发父组件方法</button>