Search code examples
angularangular-directiveangular12

How to Subscribe to some event of component using a Directive


This is my components Pagination.

<pagination
  [boundaryLinks]="true"
  [(ngModel)]="currentPage"
  [totalItems]="100"
  previousText="&lsaquo;"
  nextText="&rsaquo;"
  firstText="&laquo;"
  lastText="&raquo;"
  (pageChanged)="pageChanged($event)"
  [maxSize]="5"
  my-pagination="tableTwo"
></pagination>

And this is my Directive

@Directive ({
  selector: "pagination[my-pagination]"
})

export class MyPagination {
  constructor( private el: ElementRef){
    console.log(this.el.nativeElement.getAttribute('my-pagination'))
  }
  ngOnInit(){
  }
}

Now after getting the element in my Directive i want to use the value in my-pagination which for reference is table name(tableTwo) and scroll to the Header of the table. But I am not getting how can i know in my directive when the page has changed and perform the functionality. Need some help. Thank you :)


Solution

  • You should pass not the "table name" else the elementRef of the table. For this you can use a template reference variable

    But Angular not allow the - in names so you should change first a by some like,e.g. tableRef

    Then just use an input in your directive

    @Input() tableRef:any
    

    Your main.component becomes like

    <table #tableHead">
    ...
    </table>
    
    <pagination
      ...
      [tableRef]="tableHead"
    ></pagination>
    

    and you use like

    @Directive ({
      selector: "pagination[my-pagination]"
    })
    export class MyPagination implement AfterViewInit {
    
      @Input() tableRef:any
    
      constructor(){
      }
      ngAfterViewInit(){
         if (this.tableRef)
            this.tableRef.scrollIntoView()
      }
    }
    

    NOTE: You if you don't expect change the variable you can use @attribute

    @Directive ({
      selector: "pagination[my-pagination]"
    })
    export class MyPagination implement AfterViewInit {
    
      constructor(@Optional()@Attribute('tableRef') private tableRef: any) {
    
      ngAfterViewInit(){
         if (this.tableRef)
            this.tableRef.scrollIntoView()
      }
    }