【问题标题】:Emit event from parent to child从父级向子级发送事件
【发布时间】:2016-09-28 05:50:40
【问题描述】:

我有一个 Submitbutton in the parent component namelypersonDetails.personDetailshas manyperson` 组件。每当我单击提交按钮时,我都想在子组件中调用一个方法。

如何使用@Output 将事件从父组件发送到子组件?

从孩子到父母都很容易做到。我想访问子组件的值,因此我需要从父组件向子组件发出事件。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    您可以创建一个在您的父组件和子组件之间共享的服务,您可以在其中定义Observable,以便您可以从子组件订阅Observable,并在您从父组件收到一些值时执行一些操作。

    //common.service.ts
    
    import { Injectable, Inject } from '@angular/core';
    import { Subject }    from 'rxjs/Subject';
    @Injectable()
    export class CommonService {
      private notify = new Subject<any>();
      /**
       * Observable string streams
       */
      notifyObservable$ = this.notify.asObservable();
    
      constructor(){}
    
      public notifyOther(data: any) {
        if (data) {
          this.notify.next(data);
        }
      }
    }
    

    //parent.component.ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { CommonService } from './common.service';
    
    @Component({
      selector   : 'parent',
      templateUrl : './parent.html'
    })
    export class ParentComponent implements OnInit, OnDestroy {
      constructor( private commonService: CommonService ){
      }
    
      ngOnInit() {
        this.commonService.notifyOther({option: 'call_child', value: 'From child'});
      }
    }
    

    //child.component.ts

    import { Component, OnInit, OnDestroy } from '@angular/core';
    import { Subscription } from 'rxjs/Subscription';
    
    import { CommonService } from './common.service';
    
    @Component({
      selector   : 'child',
      templateUrl : './child.html'
    })
    export class ChildComponent implements OnInit, OnDestroy {
      private subscription: Subscription;
      constructor( private commonService: CommonService ){
      }
    
      ngOnInit() {
        this.subscription = this.commonService.notifyObservable$.subscribe((res) => {
          if (res.hasOwnProperty('option') && res.option === 'call_child') {
            console.log(res.value);
            // perform your other action from here
    
          }
        });
      }
    
      ngOnDestroy() {
        this.subscription.unsubscribe();
      }
    }
    

    【讨论】:

    • 请通过这个链接...stackoverflow.com/questions/39717465/….. 这里我提到了父子组件。请告诉我如何访问父级中的 personDetails 对象。或者我怎样才能在孩子中调用提交方法。这个问题类似于这个链接
    • 如何将事件从父 html 附加到子 .. 例如父中有一个提交按钮,当我单击它时如何在子中触发它。我可以使用 submit() 代替 ngOnInit() 吗?
    • 当您单击从parent 提交时,然后使用一些参数调用commonService 的notifyOther 并通过订阅它并根据参数值调用child 中的参数值来调用您的操作孩子。
    • 我没有获得 CommonService 的提供者!错误..我应该添加任何提供者
    • 您必须在模块或组件的提供者元数据声明中添加CommonService
    【解决方案2】:

    子组件

    在childComponent.ts

    @Input() private uploadSuccess: EventEmitter<boolean>;
    

    另外在childComponent.ts订阅事件:

    ngOnInit() {
      if (this.uploadSuccess) {
        this.uploadSuccess.subscribe(data => {
          // Do something in the childComponent after parent emits the event.
        });
      }
    }
    

    父组件

    在ParentComponent.html

    <app-gallery  [uploadSuccess] = "uploadSuccess" > </app-gallery>
    

    在ParentComponent.ts

    private uploadSuccess: EventEmitter<boolean> = new EventEmitter();
    
    onImageUploadSuccess(event) {
       console.log('Image Upload succes');
       if (event.code === 'OK' && this.maxUploadLimit > 0) {
          this.galleryImagesCount = this.galleryImagesCount + 1;
          this.maxUploadLimit = this.maxUploadLimit - 1;
        }
    
       // The parent emits the event which was given as `@Input` variable to the child-component
       this.uploadSuccess.emit(true);
    }
    

    【讨论】:

    • 完美评论。从 typescript 添加“!”:@Input() private uploadSuccess!:EventEmitter;
    猜你喜欢
    • 2019-02-22
    • 2021-04-16
    • 2019-09-21
    • 2023-03-03
    • 2017-10-18
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2021-05-27
    相关资源
    最近更新 更多