我有一个应用程序,其中有一个上传组件,可以在其中上传文件。它嵌入在中body.component。
上传时,它应使用BodyComponent.thefunction()父组件的函数(例如)(进行调用以更新数据):但仅当父组件特别是时body.component。上载也可能以其他方式用于其他行为。
诸如此类parent(this).thefunction(),该怎么做?
Answers:
我将在子组件中创建一个自定义事件。像这样:
@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) {
}
}
另一种方法是将父组件注入子组件中,但是它们将牢固地链接在一起...
@Ouput而不是@Output。可能是问题...我更新了答案。
uploadComplete is not defined注释,我只是复制了这些作为示例。父级也具有“ someMethod”,但是它已经存在问题uploadComplete。父组件确实在子节点上使用了(上载的)绑定,并且已经将子组件作为指令。
以下是最近为我工作的
class ChildComponent {
@Output() myEvent = new EventEmitter<string>();
callParent() {
this.myEvent.emit('eventDesc');
}
}
在ParentTemplate的模板中
<child-component (myEvent)="anyParentMehtod($event)"
假设我有一个ChildComponent和从中我要调用myMethod()所属的方法ParentComponent(保持原始父对象的上下文)。
@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)返回时这里发生了什么。(可能我是从根本上做错了。)
您可以将父组件注入子组件。
有关更多详细信息,请参见
-如何将父组件注入子组件?
--角2子组件是指父组件
这种方式可以确保thefunction()当父是只叫body.component。
constructor(@Host() bodyComp: BodyComponent) {
否则@Output(),首选使用子级与父级进行通信。
constructor(@Host() bodyComp: BodyComponent)..也许是最近改变了。效果很好,谢谢!
angular2/core。控制台日志显示angular2-