父组件的 angular2调用函数

我有一个应用程序,我有一个上传组件,我可以上传一个文件。它嵌入在 body.component中。

在上传时,它应该使用父组件的一个函数(例如 BodyComponent.thefunction())(调用来更新数据) : 但是只有当它的父组件是特定的 body.component时。上传也可以在其他地方以不同的行为使用。

parent(this).thefunction()这样的东西,怎么做?

121801 次浏览

I would create a custom event in the child component. Something like this:

@Component({
selector: 'child-comp',
(...)
})
export class ChildComponent {
@Output()
uploaded = new EventEmitter<string>();


uploadComplete() {
this.uploaded.emit('complete');
}

Your parent component could register on this event

@Component({
template `
<child-comp (uploaded)="someMethod($event)"></child-comp>
`,
directives: [ ChildComponent ]
})
export class ParentComponent {
(...)


someMethod(event) {
}
}

Another way would be to inject the parent component in the child one, but they will be strongly linked together...

You can inject the parent component to the child component.

For more details see
- How do I inject a parent component into a child component?
- Angular 2 child component refers to parent component This way you can ensure that thefunction() is only called when parent is a body.component.

constructor(@Host() bodyComp: BodyComponent) {

Otherwise using @Output() is preferred to communicate from child to parent.

Below is the code that worked for me in the latest

Angular 5+

class ChildComponent {
@Output() myEvent = new EventEmitter<string>();


callParent() {
this.myEvent.emit('eventDesc');
}
}

In ParentTemplate's template

<child-component (myEvent)="anyParentMethod($event)"

Solution without events involved.

Suppose that I have a ChildComponent and from that I want to call the method myMethod() which belongs to ParentComponent (keeping the original parent's context).

Parent Component class:

@Component({ ... })
export class ParentComponent {


get myMethodFunc() {
return this.myMethod.bind(this);
}


myMethod() {
...
}
}

Parent template:

<app-child [myMethod]="myMethodFunc"></app-child>

Child template

@Component({ ... })
export class ChildComponent {


@Input() myMethod: Function;


// here I can use this.myMethod() and it will call ParentComponent's myMethod()
}

In parent html:

<child [parent]="this"></child>

In child component:

@Input() parent: ParentComponent;
// then do whatever with `this.parent`

Events have their places, but I don't see anything else is simpler than this.