在Angular 8中,可以使用@Input()和@Output()装饰器以及事件发射器来在两个组件之间传递数据。
以下是一个示例,展示了如何在两个组件之间传递数据:
父组件(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Parent Component
Received data: {{ receivedData }}
`,
})
export class ParentComponent {
parentData = 'Data from parent component';
receivedData: string;
receiveData(data: string) {
this.receivedData = data;
}
}
子组件(child.component.ts):
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Child Component
Received data from parent: {{ childData }}
`,
})
export class ChildComponent {
@Input() childData: string;
@Output() childEvent = new EventEmitter();
sendData() {
this.childEvent.emit('Data from child component');
}
}
在父组件中,使用@Input()装饰器将父组件的数据传递给子组件,并使用@Output()装饰器和事件发射器将子组件的数据传递回父组件。
在子组件中,使用@Input()装饰器接收父组件传递的数据,并使用@Output()装饰器和事件发射器将子组件的数据发送到父组件。
在上面的示例中,父组件将数据"Data from parent component"传递给子组件,并通过子组件的按钮点击事件将数据"Data from child component"传递回父组件。
请注意,父组件和子组件需要在相关的模块中进行声明和导入。