Angular子组件传值给父组件

(子组件传值给父组件通过触发方法来传值方法。首先父组件传值()给子组件,子组件接收后调用父组件传来的值(方法)时会把值传给父组件)

// 方法1:

1.现在父组件news.component.ts里d定义一个接收子组件值的方法

export class NewComponent implements OnInit {
	//在这里定义和获取要传递的值,例如:
	public name = '我是发哥';
	run (){
		alert("父组件传给子组件的run方法")
	}
	//接收子组件传值的方法(参数自定义:就是子组件传过来的值)
	getDataFromChild (childData) { 
    	alert(childData)
  }
}

2.在父组件news.component.html里的子组件标签里绑定getDataFromChild方法:

    <div class="news">
    	<app-header [getDataFromChild]="getDataFromChild"></app-header>
    </div>

3.在子组件header.component.ts里接收父组件传过来的值getDataFromChild方法:

3-1.需导入Input:
   		 import { Component, OnInit ,Input} from '@angular/core';
   		 
3-2.通过 @Input()接收传过来的值
       
         @Input() getDataFromChild; //getDataFromChild方法

4.在子组件header.component.ts里定义一个方法来调用传过来的父组件方法

   export class HeaderComponent implements OnInit {
	      //通过 @Input() 引入news父组件传过来的值
	       
	        @Input() getDataFromChild;
	        public userInfo = "这是子组件的数据";
	    
	      constructor() {  }
	    
	        ngOnInit() {}
	    
		    sendParent () {
		      	this.getDataFromChild(this.userInfo)
		    }
		    
     }

5.在子组件header.component.html里绑定自己的处理方法sendParent (),也可以绑定父组件的方法来传值

<p>
    <button (click)="sendParent()">点我传值给父组件</button>
 </p>
 <p>
     <button (click)="getDataFromChild(userInfo)">点父组件传过来的方法传值给父组件</button>
 </p>

// 方法二:子组件通过@Output()方法执行父组件方法(通过执行子组件方法来触发父组件方法方法)

1.在子组件header.component.ts里引入Output,EventEmitter

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

2.在子组件header.component.ts实例化EventEmitter

 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实例广播数据(在这里定义一个方法)

resData () {
	// emit()里的参数就是要传递的值,toParent就是上面EventEmitter 实例化的对象名称toParent
  	this.toParent.emit('msg fron child')
} 

4.在父组件news.component.html里把在定义的header.component.ts里定义的方法(带个参数$event)传给子组件header.component.ts里EventEmitte的起的实例对象监听

//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>

猜你喜欢

转载自blog.csdn.net/qq_43579525/article/details/83935694