[英]How to scroll to a specific row in a specific page using Angular Material table
[英]How to access a template variable reference in a specific row of an Angular Material table? (Angular 7)
我目前正在嘗試實現以下行為的更復雜的版本,但是由於我要到周一才能訪問我的項目,因此,我將使用Angular Material教程中的一個更改示例進行簡化。
Angular Material表中填充了來自字符串數組的數據。 數據顯示在第一列的輸入字段中。 每行第二列上有一組按鈕,按下這些按鈕可更改其行輸入的內容。
我試圖通過使用模板引用變量來標識輸入元素,但是它始終顯示為未定義。 因此,我假設Angular Material的表在我背后做了一些事情,從而改變了所述變量的范圍。
<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">
<ng-container matColumnDef="inputColumn">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element">
<input #inputRef placeholder="{{element.name}}">
</td>
</ng-container>
<ng-container matColumnDef="buttonColumn">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element">
<button (click)="inputRef.value='Changed Element'">Change!</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
在我的實際項目中,數據將來自API,並且還將有更多按鈕可以啟用輸入,保存或放棄對其內容所做的更改等。 但是,如果我設法使該示例起作用,則其余部分應該很簡單。
任何幫助將不勝感激。
您可以通過使用ViewChildren
訪問表中的所有輸入元素並通過id
屬性標識它們來解決此問題。
查看此堆疊閃電戰,在那里我提出了一個快速解決方案。
基本上,我在模板中所做的就是將matInput
指令添加到您的input
元素,並通過id
屬性唯一地標識每個via(只需分配當前行element
的inputColumn
變量):
<mat-form-field>
<input matInput id="{{element.inputColumn}}" placeholder="{{element.inputColumn}}">
</mat-form-field>
在您的按鈕上添加了一個函數調用,我們在其中傳遞了當前的row element
:
<button mat-raised-button (click)="changeValue(element)">{{element.buttonColumn}}</button>
在組件中,我們使用matInput
指令檢索所有input
元素:
@ViewChildren(MatInput) matInputs: QueryList<MatInput>;
然后,在得到由我們搜索正確的按鈕調用的函數matInput
通過id
對應於element
的inputColumn
值:
changeValue(element: TableData) {
const input = this.matInputs.find(matInput => matInput.id === element.inputColumn);
input.value = 'Changed!';
}
我確定還有其他方法可以解決此問題,如果您有很多按鈕/行,則不確定如何運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.