簡體   English   中英

如何從 angular 中的父組件觸發子組件的 function?

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

我有一個 function 組件如下:

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

上述方法對我不起作用。 有人可以建議我幫忙嗎?

我認為,您的孩子應該是 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();
   }
 }

您還可以使用 Subject() 與兩個 Angular 組件通信,或使用 @ViewChild()。 有關@ViewChild 的更多信息,您可以在此處找到

我想這是“服務”概念的目的。

我的服務.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))
  }
}

父組件.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM