[英]How to trigger a function of child component from parent in angular?
I have a function component as follows:我有一个 function 组件如下:
export class ChildComp {
whoAmI() {
return 'I am a child!!';
}
}
My parent component:我的父组件:
import { ChildComp } form './child.component';
export class ParentComp {
constructor(private child: childComp ) {}
triggerChildFunction() {
this.childComp.whoAmI();
}
}
The above method did not work for me.上述方法对我不起作用。 Can anyone please suggest me help?
有人可以建议我帮忙吗?
I think, that you child should be Angular service, not just class.我认为,您的孩子应该是 Angular 服务,而不仅仅是 class。
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();
}
}
You can also communicate two Angular components with Subject(), or use @ViewChild().您还可以使用 Subject() 与两个 Angular 组件通信,或使用 @ViewChild()。 More informaction about @ViewChild you can find here
有关@ViewChild 的更多信息,您可以在此处找到
I guess it's the purpose of the concept of "Service".我想这是“服务”概念的目的。
my-service.service.ts我的服务.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 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父组件.ts
@Component()
export class ParentComponent<T> {
public whoami = 'parent';
constructor(
private myService: MyService<T>
) {}
public notifiyChild(value: T) {
this.myService.publish(value);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.