【问题标题】:How to trigger a function of child component from parent in angular?如何以角度从父级触发子组件的功能?
【发布时间】:2020-07-25 11:40:06
【问题描述】:
我有一个函数组件如下:
export class ChildComp {
whoAmI() {
return 'I am a child!!';
}
}
我的父组件:
import { ChildComp } form './child.component';
export class ParentComp {
constructor(private child: childComp ) {}
triggerChildFunction() {
this.childComp.whoAmI();
}
}
上述方法对我不起作用。有人可以建议我帮忙吗?
【问题讨论】:
标签:
javascript
angular
angular7
dom-events
angular-event-emitter
【解决方案1】:
我认为,你的孩子应该是 Angular 服务,而不仅仅是班级。
Injectable()
export class ChildService { // remember add this to module
public whoAmI() {
return 'I am a child!!';
}
}
import { ChildService } form './child.service';
export class ParentComp {
constructor(private child: childService ) {}
triggerChildFunction() {
this.childService.whoAmI();
}
}
你也可以使用 Subject() 来传递两个 Angular 组件,或者使用 @ViewChild()。有关@ViewChild 的更多信息,您可以找到here
【解决方案2】:
我想这就是“服务”这个概念的目的。
my-service.service.ts
@Injectable()
export class MyService<T> {
public stream$ = new Subject<T>();
public getSteam$() {
return this.stream$;
}
public publish(value: T) {
this.stream$.next(value);
}
}
child.component.ts
@Component()
export class ChildComponent<T> implements OnInit, OnDestroy {
public whoami = 'child';
private subscription: Subscription;
constructor(
private myService: MyService
) {}
public ngOnInit() {
this.subscription = this.myService.getStream$()
.subscribe((value: T) => {
this.functionToTrigger(value);
});
}
public ngOnDestroy() {
if(this.subscription) this.subscription.unsubscribe();
}
private functionToTrigger(arg: T) {
// do your stuff
console.log(JSON.stringify(arg))
}
}
parent.component.ts
@Component()
export class ParentComponent<T> {
public whoami = 'parent';
constructor(
private myService: MyService<T>
) {}
public notifiyChild(value: T) {
this.myService.publish(value);
}
}