在Angular 6中,可以通过使用@Input
和@Output
装饰器来从父组件向子组件传递值,从子组件向父组件传递值。
下面是一个示例,展示了如何从父组件传递值到子组件,并从子组件传递值到父组件。
父组件(parent.component.ts):
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
Received value from child component: {{childValue}}
`,
})
export class ParentComponent {
value = 'Hello from parent';
childValue: string;
handleOutputValue(value: string) {
this.childValue = value;
}
}
子组件(child.component.ts):
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Received value from parent component: {{inputValue}}
`,
})
export class ChildComponent {
@Input() inputValue: string;
@Output() outputValue = new EventEmitter();
passValueToParent() {
const value = 'Hello from child';
this.outputValue.emit(value);
}
}
在父组件中,我们使用[inputValue]
绑定将value
传递给子组件,并使用(outputValue)
绑定来处理子组件传递的值。
在子组件中,我们使用@Input
装饰器接收来自父组件的值,并使用@Output
和EventEmitter
来传递值给父组件。在passValueToParent()
方法中,我们创建一个新的值,并使用emit()
方法将其传递给父组件。
通过这种方式,我们可以在父组件和子组件之间传递值。