Подтвердить что ты не робот

Излучение события от родителя к ребенку

У меня есть button in the parent component namely Отправить" button in the parent component namely personDetails . У personDetails has many компонентов человека. Всякий раз, когда я нажимаю кнопку "Отправить", я хочу вызвать метод в дочернем компоненте.

Как я могу @Output событие из родительского в дочерний компонент, используя @Output?

Это легко сделать от ребенка к родителю. Я хочу получить доступ к значению дочернего компонента, поэтому мне нужно передать событие от родителя к потомку.

4b9b3361

Ответ 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();
  }
}

Ответ 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);
}