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

问题描述 投票:-1回答:2

我具有如下功能组件,

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 javascript-events angular7 angular-event-emitter
2个回答
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);
  }
}

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

© www.soinside.com 2019 - 2024. All rights reserved.