Angular 从组件到 app.component 的 EventEmitter

Angular EventEmitter from component to app.component

我想将子组件的事件发射器绑定到父组件,但父组件是“app.component”,因此我假设两者之间的关系未声明而是隐含的。
answer 中,我看到了如何将事件发射器添加到已在他的父级中明确声明为子级的子级:

<child (notifyParent)="getNotification($event)"></child>

但是在我的应用程序中,子组件(让我们调用 id:child)不是以这种方式声明的,而是在 app.module 中声明为路由:

const appRoutes: Routes = [
  { path: '**',      component:  Child}
];

此组件基本上代表站点的启动页面,并且在未提供完整身份验证的情况下也用作防护中的重定向。
我想做的是向 child 添加一个事件发射器,通知 app.module 发生变化。
我已经在 child 中实现了一个带有 @Output() 装饰器的 EventEmitter,我还实现了将在 app.module 中调用的方法,但我就是找不到地方在两个组件中的何处注册此绑定。
由于所有组件都是 app.component 的子组件,难道 app.component 不应该提供一种方法来注册来自其子组件的传入输入,而不需要先明确地将它们声明为子组件吗?

当您的 'child' 组件在您的 'parents' html 模板中调用时,会给出父子组件关系。因此,如果您的组件在 app.components html 模板中,那么它是 app.component 的子项,您可以使用 EventEmitters 在两者之间传递数据。

如果这两者之间有另一个组件,那么您必须使用服务来共享数据。

好吧,根据我的理解,您必须显式绑定 app.componentchild.component 才能真正使事件发射器工作。

根据您的情况,您也可以考虑使用 Subject 来实现相同的目的。您不必为每个 child.component 明确定义,您可以简单地订阅并监听正在发生的任何变化。

I have created one link to help two sibling & parent components talk。您可以对多个 child 和一个 parent

执行相同的操作

app.component.html

<br />
Enter a name:
<input type="text" [(ngModel)]="myTextVal">
<button (click)="sendTextValue()">Click Me to emit to Hello Component</button>
<hello></hello>

app.component.ts

export class AppComponent  {
  myTextVal: string;

  constructor(private appService: AppService){}

  sendTextValue(){
    this.appService.passValue(this.myTextVal);
  }
}

app.service.ts

@Injectable()
export class AppService {

  public stringSubject = new Subject<string>();

  passValue(data) {
    //passing the data as the next observable
    this.stringSubject.next(data);
  }

}

hello.component.ts


@Component({
  selector: 'hello',
  template: `<h1>Hello {{name}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent {
  name: string;

  constructor(private appService: AppService) {

  }

  ngOnInit() {
    this.appService.stringSubject.subscribe(
      data => 
      {
        console.log('next subscribed value: ' + data);
        this.name = data;
      }
    );
  }
}

您必须添加

<child (notifyParent)="getNotification($event)"></child>

在您的父组件模板中,即在您的情况下为 app.component,以便收听 "notifyParent" 事件。将方法实现从 app.module 移动到 app.component.ts 文件中,它将起作用。