从父组件到子组件传递数据
- 使用@Input装饰器
- 原理:在子组件中通过
@Input()
装饰器来定义一个输入属性,父组件可以通过绑定该属性来传递数据。
- 示例:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app - child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() parentData: string;
}
- **子组件模板(child.component.html)**:
<p>从父组件接收到的数据: {{parentData}}</p>
- **父组件(parent.component.ts)**:
import { Component } from '@angular/core';
@Component({
selector: 'app - parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
dataToChild = '这是来自父组件的数据';
}
- **父组件模板(parent.component.html)**:
<app - child [parentData]="dataToChild"></app - child>
从子组件向父组件传递数据
- 使用@Output装饰器和EventEmitter
- 原理:在子组件中通过
@Output()
装饰器和EventEmitter
类来定义一个事件输出,当子组件中某些逻辑触发时,通过EventEmitter
的emit
方法发射数据,父组件通过绑定该事件来接收子组件传递的数据。
- 示例:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app - child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output() childData = new EventEmitter<string>();
sendDataToParent() {
this.childData.emit('这是来自子组件的数据');
}
}
- **子组件模板(child.component.html)**:
<button (click)="sendDataToParent()">点击向父组件发送数据</button>
- **父组件(parent.component.ts)**:
import { Component } from '@angular/core';
@Component({
selector: 'app - parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
receivedData: string;
handleChildData(data: string) {
this.receivedData = data;
}
}
- **父组件模板(parent.component.html)**:
<app - child (childData)="handleChildData($event)"></app - child>
<p>从子组件接收到的数据: {{receivedData}}</p>