我有两个共享组件,我希望父级在其子级中调用一个方法
共享组件1(父级)
@Component({
selector: 'parent',
template: `<div>
<div #parentBody>
<ng-content select="[parentBody]"></ng-content>
</div>
<button (click)=" " >tell child to dance</button>
</div>
`,
})
export class ParentComponent {
constructor() { }
}
共享组件2(子组件)
@Component({
selector: 'child',
template: `<div>
<p>I'm a child component</p>
</div>
`,
})
export class ChildComponent {
dance() {
alert('dancing');
}
}
和应用内组件
<parent>
<div parentBody>
<child></child>
</div>
<parent>
在这种情况下,我们如何在父子组件之间进行通信
答案 0 :(得分:3)
parent.component.ts :
Route::delete('admin-delete/{id}', 'UsersController@removeAdminDelete');
app.component.html :
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'parent',
template: `
<div>
<div #parentBody>
<ng-content select="[parentBody]"></ng-content>
</div>
<button (click)="dance.emit()">tell child to dance</button>
</div>
`
})
export class ParentComponent {
@Output() dance = new EventEmitter();
}
选中使用{@ 3}方法的simple StackBlitz DEMO
(在@trichetriche评论此问题后添加。谢谢@trichetriche!)
parent.component.ts :
<parent (dance)="myChild.dance()">
<div parentBody>
<child #myChild></child>
</div>
<parent>
app.component.html :
import { Component, Input, ContentChild } from '@angular/core';
import { IChild } from './i-child';
@Component({
selector: 'parent',
template: `
<div>
<div #parentBody>
<ng-content select="[parentBody]"></ng-content>
</div>
<button (click)="onClick()">tell child to dance</button>
</div>
`
})
export class ParentComponent {
@ContentChild('myChild') child: IChild;
onClick() {
this.child.dance();
}
}
选中使用{ContentChild方法的simple StackBlitz DEMO
这两种方法都可以很好地满足您的要求。