Search code examples
angularparent-childonchangeeventemitterevent-binding

Is there a method to trigger a function on emit event and not only onChange?


When I press an arrow in the parent element I always emit true. The child receives the change only at the beginning when the emitter changes from undefined to true. Is there a method to call the function always when the parent emitts something even it's the same value as the lat time?

Parent HTML:

<div (click)="emit()">
<child [changed_slide]= "changed_slide"></child>

Parent .ts:

emit(){this.changed_slide.emit(true);}

Child:

ngOnChanges(changes: { [property: string]: SimpleChange }){
    let change: SimpleChange = changes['changed_slide'];
    console.log(change);
    }

So I want that every time I click the parent div "true" will be emitted (or everything else, I just want something to be emitted in order to do something in the child) and then one function will be automatically triggered in the child. Every time I click the parent the child does something. I would appreciate any ideas, Thank you!


Solution

  • Like you are sending data from a Parent to a Child element you could use a set in the Child @Input:

    **Child**
        private _changed_slide: boolean;
        @Input() public set changed_slide(value: boolean) {
           this._changed_slide = value;
        }
    

    Then in your parent, you can do:

    export class ParentComponent {
        private eventSource: Subject<boolean>;
        public event$: Observable<boolean>;
        constructor() {
         this.eventSource = new Subject();
         this.event$ = this.eventSource.asObservable();
        }
    
        emit() {
          this.eventSource.next(true);
        }
    }
    

    Html:

    <div (click)="emit()">
    <child [changed_slide]= "event$ | async"></child>