@Input装饰器的作用
- 数据流入组件:
@Input
装饰器用于将数据从父组件传递到子组件。它允许父组件向子组件传递数据,使得子组件能够接收并使用父组件提供的值。
- 属性绑定:在父组件的模板中,通过属性绑定的方式将数据传递给子组件中使用
@Input
装饰的属性。
在父子组件通信中使用@Input传递数据的示例
- 子组件定义:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input() childData: string;
}
- 子组件模板(child.component.html):
<p>从父组件接收到的数据: {{ childData }}</p>
- 父组件模板(parent.component.html):
<app-child [childData]="parentData"></app-child>
- 父组件定义(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
parentData = '这是来自父组件的数据';
}
@Output装饰器的作用
- 事件流出组件:
@Output
装饰器用于让子组件向父组件发送事件。子组件可以在特定情况下触发一个事件,父组件可以监听这个事件并做出相应的处理。
- 事件绑定:在父组件模板中,通过事件绑定的方式监听子组件发出的事件。
在父子组件通信中使用@Output传递事件的示例
- 子组件定义:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Output() childEvent = new EventEmitter();
sendEvent() {
this.childEvent.emit('子组件触发了事件');
}
}
- 子组件模板(child.component.html):
<button (click)="sendEvent()">触发事件</button>
- 父组件模板(parent.component.html):
<app-child (childEvent)="handleChildEvent($event)"></app-child>
- 父组件定义(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent {
handleChildEvent(data: string) {
console.log('接收到子组件的事件数据:', data);
}
}