问题描述
2角 - 如何可以将子组件到父组件说话
Angular 2 - how can a child component speak to a parent component?
我用@input为父母和孩子之间的正常工作。
I used @input for parent to child which works fine.
我会怎么用做孩子家长吗?
What would I use to do child to parent?
这是我的编译器错误,我得到:
推荐答案
您可以使用 @Output
来触发子组件的事件。家长可以在他们注册的处理。
You can use @Output
to trigger events from the child component. The parent one can register processing on them.
下面是一个示例
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
@Output()
someEvent: EventEmitter;
constructor() {
this.someEvent = new EventEmitter();
}
triggerEvent() {
this.someEvent.emit('some value');
}
}
和其在父组件使用:
<child (some-event)="printValue($event)"></child>
FYI $事件
包含值'某个值'
。
您可以看到,Angular2支持双向在这个级别绑定:
You can notice that Angular2 supports two-way binding at this level:
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
@Input()
value:string
@Output()
valueChanges: EventEmitter;
constructor() {
this.valueChanges = new EventEmitter();
}
triggerUpdated() {
this.valueChanges.emit('some value');
}
}
和其在父组件使用:
<child [(value)]="someVar"></child>
修改
要调用父组件的方法,你需要把它注入到孩子之一。
To call a method from the parent component, you need to inject it into the child one.
您需要小心在这个水平,以循环依赖进口,并且提升不支持类(使用类的创建之前)。
You need to be careful at this level to cyclic dependency in imports and that hoisting isn't supported for classes (use a class before it's created).
有关详细信息,请参阅本答案:
See this answer for more details:
- 。
- How can i access the values from parent component in angular2 using dependency injection?.
下面是一个例子:
@Component({
selector: 'child',
(...)
})
export class ChildComponent {
constructor(@Inject(forwardRef(() => AppComponent)) parent:ParentComponent) {
(...)
}
}
本文还可以给你一些提示:
This article could also give you some hints:
- 的
蒂埃里
这篇关于角2 - 怎么能一个子组件到父组件说话?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!