Angular ViewChild custom sort selector

本小妞迷上赌 提交于 2019-12-10 22:34:09

问题


I'm learning about angular ViewChild currently, but I seem to be missing something when using ViewChild to select custom reference variables from the DOM.

In my template I have two tables:

<mat-table #eventTable [dataSource]="eventDataSource" matSort>
<mat-table #eventDateTable [dataSource]="dateEventDataSource" matSort>

I am attempting to target them with a sort for each:

@ViewChild('eventTable') eventTableSort: MatSort;
@ViewChild('eventDateTable') eventDateTableSort: MatSort;

Then I attempt to initiate them in ngAfterViewInit():

this.eventDataSource.sort = this.eventTableSort;
this.dateEventDataSource.sort = this.eventDateTableSort;

The result is nothing happens on either table when I click the headers to sort each column. I'm sure there is something simple I am overlooking here but I can't see what it is. How can I make each of these tables sort independently of each other?


回答1:


I had been attempting to follow this question to derive and answer but it wasn't making sense to me. So I dove into a debugger and found an answer to my question.

When declaring a reference variable (#eventTable and #eventDateTable) you are creating a reference to the element/component/directive that you have declared it on. In my example I was creating a reference to each <mat-table> I had created. I was then attempting to assign these tables themselves to the eventTableSort and eventDateTableSort values. In ngAfterViewInit() I was essentially saying to set the sort for each dataset equal to the table it's stored in.

The correct way to go about targeting the MatSort for each table is to declare it when setting your reference variables. Rather than #eventTable which will create a reference for the whole table, #eventTable="matSort" will create a reference directly to that table's MatSort object. Then in your component you can use a ViewChild to target the MatSort itself.

Here are the same code I have written above now working correctly:

<mat-table #eventTable="matSort" [dataSource]="eventDataSource" matSort>
<mat-table #eventDateTable="matSort" [dataSource]="dateEventDataSource" matSort>

@ViewChild('eventTable') eventTableSort: MatSort;
@ViewChild('eventDateTable') eventDateTableSort: MatSort;

this.eventDataSource.sort = this.eventTableSort;
this.dateEventDataSource.sort = this.eventDateTableSort;


来源:https://stackoverflow.com/questions/48405373/angular-viewchild-custom-sort-selector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!