【发布时间】:2016-06-26 17:50:26
【问题描述】:
我有一个应用程序,其中有一个可以上传文件的上传组件。它嵌入在body.component 中。
在上传时,它应该使用父组件的一个函数(例如BodyComponent.thefunction())(调用更新数据):但前提是它的父组件是body.component。上传也可能在其他地方以不同的行为使用。
类似parent(this).thefunction(),怎么做?
【问题讨论】:
标签: angular
我有一个应用程序,其中有一个可以上传文件的上传组件。它嵌入在body.component 中。
在上传时,它应该使用父组件的一个函数(例如BodyComponent.thefunction())(调用更新数据):但前提是它的父组件是body.component。上传也可能在其他地方以不同的行为使用。
类似parent(this).thefunction(),怎么做?
【问题讨论】:
标签: angular
我会在子组件中创建一个自定义事件。像这样的:
@Component({
selector: 'child-comp',
(...)
})
export class ChildComponent {
@Output()
uploaded = new EventEmitter<string>();
uploadComplete() {
this.uploaded.emit('complete');
}
您的父组件可以注册此事件
@Component({
template `
<child-comp (uploaded)="someMethod($event)"></child-comp>
`,
directives: [ ChildComponent ]
})
export class ParentComponent {
(...)
someMethod(event) {
}
}
另一种方法是将父组件注入到子组件中,但它们会紧密联系在一起......
【讨论】:
angular2/core 导入在顶部的打字稿中定义的。控制台日志显示 angular2-polyfills 存在问题
@Ouput 而不是@Output。这可能是问题...我更新了我的答案。
uploadComplete is not defined 请注意,我只是复制了这些作为示例。父级也有“someMethod”,但它已经有uploadComplete 的问题。父组件确实在子节点上使用(上传的)绑定,并且它已经将子节点作为指令。
下面是最新的对我有用的代码
class ChildComponent {
@Output() myEvent = new EventEmitter<string>();
callParent() {
this.myEvent.emit('eventDesc');
}
}
在ParentTemplate的模板中
<child-component (myEvent)="anyParentMethod($event)"
【讨论】:
假设我有一个ChildComponent,并且我想调用属于ParentComponent 的方法myMethod()(保留原始父级的上下文)。
@Component({ ... })
export class ParentComponent {
get myMethodFunc() {
return this.myMethod.bind(this);
}
myMethod() {
...
}
}
<app-child [myMethod]="myMethodFunc"></app-child>
@Component({ ... })
export class ChildComponent {
@Input() myMethod: Function;
// here I can use this.myMethod() and it will call ParentComponent's myMethod()
}
【讨论】:
this.myMethod.bind(this) 被返回时,我实际上并不确定这里发生了什么。 (可能我在做一些根本错误的事情。)
您可以将父组件注入到子组件中。
有关详细信息,请参阅
- How do I inject a parent component into a child component?
- Angular 2 child component refers to parent component
这样,您可以确保仅在父级为 body.component 时才调用 thefunction()。
constructor(@Host() bodyComp: BodyComponent) {
否则,最好使用@Output() 来实现子级与父级之间的通信。
【讨论】:
constructor(@Host() bodyComp: BodyComponent).. 也许它最近被改变了。效果很好,谢谢!