【问题标题】:Angular EventEmitter from component to app.component从组件到 app.component 的 Angular EventEmitter
【发布时间】:2018-09-28 15:32:42
【问题描述】:

我想将一个事件发射器从一个子组件绑定到一个父组件,但父组件是“app.component”所以我假设两者之间的关系不是声明的而是隐含的。
this 答案中,我看到了如何将事件发射器添加到已在其父级中明确声明的子级:

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

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

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

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

【问题讨论】:

  • 看看this answer
  • 看看我的回答。这是一种不同的方法,我认为会有所帮助

标签: angular angular5 eventemitter


【解决方案1】:

好吧,据我了解,您必须明确绑定 app.componentchild.component 才能真正使事件发射器工作。

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

I have created one link to help two sibling & parent components talk。您可以为几个孩子和一个父母做同样的事情

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

【讨论】:

  • @AngryCoder :它以某种方式过期。请立即检查。 :) 谢谢
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    你必须添加

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

    在您的父组件模板中,即您的案例中的 app.component,以便监听“notifyParent”事件。将方法实现从 app.module 移到 app.component.ts 文件中,它会起作用。

    【讨论】:

    • 嗨,谢谢,但我实际上是在问是否有替代方案,但我感谢您的回复
    • 您可以通过在共享服务中声明它来使用主题,并在每次发出事件时向该主题推送一个 $event。并在你的 app.component 中订阅这个主题
    猜你喜欢
    • 2020-09-10
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 2017-07-22
    • 2017-12-30
    • 1970-01-01
    相关资源
    最近更新 更多