-
父传子
父组件:定义变量并通过中括号注入
<p>father </p> <app-child [message]="message"></app-child>
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
constructor() { }
fatherMsg = '这是父组件的message'
ngOnInit(): void {
}
}
子组件:@Input接收后即可使用
<p>child:{{message}}</p>
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Input() fatherMsg: any
ngOnInit(): void {
}
}
2.子传父
-
@ViewChild
通过ViewChild(‘视图节点名’)来修饰一个自己属性名,将子组件的整个组件对象赋予给了属性,以此来获取子组件里的方法与变量名
父组件:
<!--在父组件中通过#来定义子组件的视图节点名-->
<app-child #childComponent></app-child>
<button (click)="getChild()">触发事件</button>
//导入ViewChild装饰器
import {Component, OnInit, ViewChild} from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
constructor() { }
//通过ViewChild('视图节点名')来修饰一个自己的属性名,等于将子组件的整个组件对象赋予给了属性
@ViewChild('childComponent') childComponent: any
ngOnInit(): void {
}
getChild() {
//通过属性名来获取子组件的属性与方法
this.childComponent.childMethod() //执行子组件的方法
console.log(this.childComponent.childMeg) //打印子组件的变量
}
}
子组件:
import { Component, OnInit} from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
childMeg: string = '这是子组件的message'
ngOnInit(): void {
}
childMethod() {
console.log('执行了子组件的方法')
}
}
- @Output()
父组件:
通过监听EventEmitter实例的变量名。来监听广播,通过$event来获取到子组件传递的值。
<!-- 这边通过将 $event当作形参传入方法中--!>
<app-child (childSend)="getChild($event)"></app-child>
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-father',
templateUrl: './father.component.html',
styleUrls: ['./father.component.css']
})
export class FatherComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
getChild(e: any) {
console.log(e)
}
}
子组件
- 必须在子组件中导入output跟EventEmitter 为事件驱动
- 然后通过@Output()来修饰一个EventEmitter实例的变量
- 定义触发传值的触发事件
- 通过EventEmitter实例的变量名来广播所要传递值与方法
<!--定义发送事件,这里通过 点击按钮后将子组件中的数值与方法传递给父组件!-->
<button (click)="send()">子组件发送值给父组件</button>
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
constructor() { }
@Output() public childSend = new EventEmitter()
ngOnInit(): void {
}
send() {
this.childSend.emit('来自子组件的数据')
}
}