在Angular 6中,可以通过@Input装饰器将值从父组件传递到子组件。然后,在子组件中使用@Output装饰器和EventEmitter来将值发送回父组件。
以下是一个代码示例,显示了如何从父组件将值传递给子组件,并将其传递回调用方法:
在父组件my-parent.component.ts中:
import { Component } from '@angular/core';
@Component({
selector: 'my-parent',
template:
})
export class MyParentComponent {
myValue = 'Hello world';
onChildValueChange(value: string) { console.log('Received from child component: ', value); } }
在子组件my-child.component.ts中:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'my-child',
template:
})
export class MyChildComponent {
@Input() parentValue: string;
@Output() childValueEvent = new EventEmitter{{ childValue }}
childValue = 'Child value';
// Call this method when you want to emit a new value to parent. emitNewValue() { // Do some processing here to change 'childValue'. // Then, emit it to parent. this.childValueEvent.emit(this.childValue); } }
在这个例子中,我们使用@Input装饰器将myValue变量从父组件传递到子组件,并在子组件中将其存储为parentValue。然后,使用@Output装饰器和EventEmitter创建childValueEvent事件,以便在子组件中发出新的值。
最后,在子组件的emitNewValue方法中,我们可以更改childValue的值,并通过childValueEvent事件将其传递回父组件。在父组件中,我们将onChildValueChange方法链接到childValueEvent事件处理程序,以便在子组件发出新值时调用它。
这个例子显示了如何通过@Input和@Output装饰器在Angular 6中将值从父组件传递到子组件,并将其传递回回调方法。