我可以在Angular 2中从父级发送事件到子级

时间:2016-09-28 05:50:40

标签: javascript html angular typescript

我在父类中提交了按钮personDetails

personDetails有很多人类。

每当我点击提交按钮时,我想在子类中调用一个方法。

如何使用output从父对象发出方法?

从孩子到父母很容易做到。我想访问子组件的html值,因此我需要从父级发送一个事件。

2 个答案:

答案 0 :(得分:31)

您可以创建一个在您的父组件和子组件之间共享的服务,您可以在其中定义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();
  }
}

答案 1 :(得分: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);
}