0

Parent HTML:

<ng-container *ngFor="let doc of documents">
    <child [clickEvent]="eventSubject.asObservable()" [document]="doc"></child>
 </ng-container>

Parent Class:

eventSubject: Subject<boolean> = new Subject<boolean>();
onclick(event)  {
    this.eventSubject.next(event)
}

Child Class:

@Input() keyEvent: Observable<boolean>;

this.keyEvent
    .subscribe(res => {
      console.log(res);
    })

Because I bind the event inside an *ngFor, it sends the value as much as my array length. Its essential that I get the last or one value of the emitted in the observable. What can be done?

I tried using the take and last operators, but they complete the stream.

Ahmet Ömer
  • 614
  • 1
  • 10
  • 18

2 Answers2

1

You can put the if condition in HTML

Solution 1

 <ng-container *ngFor="let doc of documents; last as last">
    <child *ngIf= "!last" [document]="doc"></child>
    <child *ngIf= "last" [clickEvent]="eventSubject.asObservable()" [document]="doc"></child>
 </ng-container>

Solution 2

Just handle it in ts file instead. Make the following changes -

in html

<ng-container *ngFor="let doc of documents; last as last">
    <child [clickEvent]="handlClick(last)" [document]="doc"></child>
 </ng-container>

in ts

handlClick(isLast){
   if(isLast){
     return eventSubject.asObservable();
   }
}
Sunil Singh
  • 11,001
  • 2
  • 27
  • 48
0

Use BehaviorSubject instead of Subject. It has getValue() method which gives you current emitted value.

Check out this answer

Sarthak Aggarwal
  • 2,284
  • 1
  • 8
  • 12