mardi 14 janvier 2020

Subscribe Event In Component That Are Not Sibling/Parent (Angular)

I am following this to emit and subscribe event to listen mat-sidenav open/close event , for this I made a middle listener service which listen for change and fire event like

FullComponent Service

export class FullCompServiceService {
isOpen = false;

 @Output() opened: EventEmitter<boolean> = new EventEmitter();

 @Output() filterParameterChange = new EventEmitter();


 @Output() ColCbxChangeEvent = new EventEmitter();

  constructor() { }

  //this will only called by subscribers
   changeFilter(columns){


    this.filterParameterChange.emit({columns:columns})

   }

      toggle() {
     console.log("toggle received");
     this.isOpen = !this.isOpen;

     this.opened.emit(this.isOpen);

     }


      columnCheckChange(check,value){
      this.ColCbxChangeEvent.emit({check:check,value:value});

       }
   }

FullComponent

  export class FullComponent implements OnInit {


  columns=[];
  constructor(private fullcompService: FullCompServiceService) {


    //Filter change listener which is trigger by subscriber components using **FullCompService**
  ngOnInit() {
  this.fullcompService.filterParameterChange.subscribe(paraChange => {
   this.columns=paraChange.columns;
    });

   console.log("received filter = "+this.columns);
 }

   toggleColumnsCbx(check,value){

    this.fullcompService.columnCheckChange(check,value);


   }

      toggleFilter(){

       this.fullcompService.toggle();


      }

Subscriber Component

This does not trigger on open change inside service

  @Component({
  selector: 'app-site-search',
  providers:[FullCompServiceService],
  templateUrl: './site-search.component.html',
   styleUrls: ['./site-search.component.scss']


 })


  export class SiteSearchComponent implements OnInit,OnDestroy {



  ngOnInit() {


   debugger;
  //Filter open subscriber
   this.fullcompService.opened.subscribe(isOpen => {
  debugger;
  console.log("received toggle inside sitesearch from fullcomp");
  if(isOpen){

    //check if current page name matches
     console.log("sending..."+this.siteSearchCbx);
    this.fullcompService.changeFilter(this.siteSearchCbx);
  }
}); 

 }

}

The exception in my case if file structure of components ,it seems like it is because they are not inside same directory.

Aucun commentaire:

Enregistrer un commentaire