如何从角度触发父组件的子组件功能?

时间:2020-04-12 22:21:09

标签: javascript angular angular7 dom-events angular-event-emitter

我具有如下功能组件:

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

以上方法对我不起作用。有人可以建议我帮忙吗?

2 个答案:

答案 0 :(得分:0)

我认为,您的孩子应该服从于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

答案 1 :(得分:0)

我想这是“服务”概念的目的。

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