[英]how to get updated Viewchildren reference after sorting in angular MatTable
我正在處理角形材質表,並希望使用ViewChildren
和ViewContainerRef
獲取tableRow參考。
HTML片段
<tr mat-row *matRowDef="let row; columns: displayedColumns;" #tableRows ></tr>
和TS代碼段
@ViewChildren('tableRows', {read: ViewContainerRef}) rowContainers
我可以獲取表行的引用,但是問題是當我進行排序時,我無法在rowContainers
變量中獲取更新的DOM引用。
我找不到任何刷新rowContainers
變量的方法。
有人知道如何刷新ViewChildren
變量嗎?
您可以在stackblitz中查看行為。
我想你要數組的第一個元素,而不是ViewChildren。 向rowContainers.changes過渡,不起作用,但是,當您使用MatTableDataSource時,您始終可以使用其methond _orderData(需要元素數組),例如,您可以編寫類似
let orderData=this.dataSource._orderData(this.dataSource.data)
console.log(orderData[0])
更新如果要訂購ViewChildren,則需要將viewChildren傳遞給數組,對數組進行排序並進行重置。 如果我們的viewChildren是“ ViewContainerRef”
@ViewChildren('tableRows', {read: ViewContainerRef}) rowContainers: QueryList<any>
//We can access to the content using, e.g.
rowContainers.first.element.nativeElement.textContent;
如果我們的ViewChildren是“ ElementRef”
@ViewChildren('tableRows', {read: ElementRef}) rowContainers: QueryList<any>
//We can access to the content using, e.g.
rowContainers.first.nativeElement.textContent;
所以,當我們點擊
rowClick(table:any) {
//get the order data
const orderData=this.dataSource._orderData(this.dataSource.data);
//convert rowContainers to array
const array=this.rowContainers.toArray();
//sort the array
array.sort((a,b)=>{
//the content of "a" and "b"
//e.g. will be " 3 Lithium 6.941 Li"
let contentA=a.element.nativeElement.textContent;
let contentB=b.element.nativeElement.textContent;
//get the index in our orderData
let indexA=orderData.findIndex(d=>''+d.position==contentA.split(' ')[1])
let indexB=orderData.findIndex(d=>''+d.position==contentB.split(' ')[1])
//return 0 if equal, 1 if greater, -1 if less
return indexA==indexB?0:indexA>indexB?1:-1;
})
//make a reset
this.rowContainers.reset(array);
console.log(this.rowContainers.first.element.nativeElement.textContent);
this.firstElement = this.rowContainers.first;
}
Update2如果我們將該表作為ViewChild
@ViewChild(MatTable, {read:ElementRef}) table
我們可以使用其nativeElement.textContent,因此
rowClick(table:any) {
const array=this.rowContainers.toArray();
//using context the table
const tableArray=this.table.nativeElement.textContent.split(' ')
let order:any[]=[]
for (let i=9;i<tableArray.length;i+=8)
order.push(tableArray[i])
array.sort((a,b)=>{
let contentA=a.element.nativeElement.textContent;
let contentB=b.element.nativeElement.textContent;
let indexA=order.findIndex(d=>d==contentA.split(' ')[1])
let indexB=order.findIndex(d=>d==contentB.split(' ')[1])
return indexA==indexB?0:indexA>indexB?1:-1;
})
this.rowContainers.reset(array);
console.log(this.rowContainers.first.element.nativeElement.textContent);
this.firstElement = this.rowContainers.first;
}
你的分叉式閃電戰
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.