angular2 父子组件之间的通信与传值
1. 父组件给子组件传值
父组件可以给子组件传值,方法或者是将整个父组件传给子组件
1. 在父组件的 ts 文件中定义一个变量
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
public title: string = '父组件传入的 title';
public message: string = '父组件传入的 message';
constructor() {
}
ngOnInit(): void {
}
run() {
alert('父组件的 run()');
}
}
2. 在父组件的 html 文件中,在引用子组件的标签中设置相关属性用来接收父组件传来的值
<p>parent works!</p>
<hr>
<app-child [title]="title" [message]="message" [run]="run" [parent]=this></app-child>
3. 子组件的 html
<p>child works!</p>
<p>父组件传来的 title -- {{title}}</p>
<p>父组件传来的 message -- {{message}}</p>
<hr>
<button (click)="parentRun()">执行父组件的方法</button>
4. 在子组件中引入 Input 模块,接收传入的值
import {Component, OnInit, Input} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
/**
* 接收父组件传来的 title
*/
@Input()
public title: string;
/**
* 接收父组件传来的 message
*/
@Input()
public message: string;
/**
* 接收父组件传来的 run()
*/
@Input()
public run: Function;
/**
* 接收整个父组件
*/
@Input()
public parent: any;
constructor() {
}
ngOnInit(): void {
}
parentRun() {
//调用父父组件的方法
this.run();
}
}
2. 子组件给父组件传值、执行子组件的方法
1. 父组件的 html
<p>parent works!</p>
<button (click)="getChildMessage()">获取子组件的 message</button>
<button (click)="runChild()">执行子组件的方法</button>
<hr>
<app-child #child></app-child>
2. 父组件的 ts – 引入 ViedChild 模块
import { Component, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
@ViewChild('child')
public child: any;
constructor() { }
ngOnInit(): void {
alert(this.child.message);
}
getChildMessage() {
//获取子组件的 message
alert(this.child.message);
}
runChild() {
//执行子组件的 run()
alert(this.child.run())
}
}
3. 子组件的 ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
public message: string = '子组件的 message';
constructor() { }
ngOnInit(): void {
}
run(){
alert('子组件的 run()')
}
}