简体   繁体   中英

How to trigger a function of child component from parent in angular?

I have a function component as follows:

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.

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(). More informaction about @ViewChild you can find here

I guess it's the purpose of the concept of "Service".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM