首页 文章

Angular:在一个组件中调用一个函数,在另一个组件上调用事件

提问于
浏览
-2

使用Angular6,假设我有2个子组件A,B,它们都是父组件P的一部分 . 我想在组件A上使用表单输入,所以一旦单击,字符串值将在组件B上传递 and trigger a function . 这或许:

functionOnB(valueFromA: string) { //some code here; }

这有可能吗?

我使用angular的EventEmitter成功地在组件之间传输数据,但是可以用这些数据调用函数,而不仅仅是传递原始信息吗?

2 回答

  • 0

    是的,您可以使用@Input装饰器将Component引用传递给另一个Component . 这样,您就可以从ComponentA调用ComponentB方法 .

    例如,在FirstComponent中,您声明一个SecondComponent类型的实例变量:

    @Input()
     second: SecondComponent;
    

    在您的父HTML中,您传递了组件引用:

    <app-first [second]="second"></app-first>
     <app-second #second></app-second>
    

    Component Interaction Cookbook

    这里有一个有效的例子:Component Interaction Example

  • 0

    可以使用公共服务从另一个组件触发事件/功能 . 例如:ComponentA的click事件将调用服务方法 . 然后,该服务方法应该发出另一个事件 . 然后ComponentB应订阅服务的事件 Launcher . 示例代码:ChildA(HTML):

    <button (click)="onClick()"></button>
    

    ChildA控制器(TS):

    onClick() {
        this.commonService.AClicked('Component A is clicked!!');
      }
    

    共同服务(TS):

    import { Injectable, EventEmitter, Output } from '@angular/core';
    
    @Output() aClickedEvent = new EventEmitter<string>();
    
    AClicked(msg: string) {
      this.aClickedEvent.emit(msg);
    }
    

    ChildB控制器(TS):

    ngOnInit() {
        this.commonService.aClickedEvent
        .subscribe((data:string) => {
          console.log('Event message from Component A: ' + data);
        });
      }
    

相关问题