gpt4 book ai didi

Angular:从外部访问 ng-content 嵌套组件方法

转载 作者:行者123 更新时间:2023-12-03 08:57:14 24 4
gpt4 key购买 nike

我有两个共享组件,我希望父组件调用其子组件中的方法

共享组件 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>

在这种情况下我们如何在父组件和子组件之间进行通信

最佳答案

您可以通过两种方式实现:

1) 父组件中的@Output参数。

parent.component.ts:

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();
}

app.component.html:

<parent (dance)="myChild.dance()">
<div parentBody>
<child #myChild></child>
</div>
<parent>

Check this simple StackBlitz DEMO which is using @Output approach


2) 父组件中的@ContentChild参数。

(在@tricheriche评论此问题后添加。感谢@tricheriche!)

parent.component.ts:

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();
}
}

app.component.html:

<parent>
<div parentBody>
<child #myChild></child>
</div>
<parent>

Check this simple StackBlitz DEMO which is using @ContentChild approach


无论哪种方式都可以很好地满足您的要求。

关于Angular:从外部访问 ng-content 嵌套组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54304318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com