#html #angular #typescript #spring-boot
#HTML #angular #typescript #spring-boot
Вопрос:
У меня есть следующий HTML-файл для отображения некоторых значений:
<h1 mat-dialog-title color="primary">
License Details
</h1>
<mat-dialog-content >
<div style="width:100%;display: flex;flex-direction: column;">
</div>
</mat-dialog-content>
<mat-dialog-content>
<div class="example-container mat-elevation-z8">
<table mat-table [dataSource]="customerList" class="a">
<ng-container matColumnDef="Customer ID" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef class="customtd" style="font-size:15px;"><strong>Customer Id*</strong></th>
<td mat-cell *matCellDef="let element" class="customtd"> {{element.customerId}} </td>
</ng-container>
<ng-container matColumnDef="Hardware Key" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef class="customtd" style="font-size:15px;"><strong>Hardware Key</strong></th>
<td mat-cell *matCellDef="let element" class="customtd"> <textarea rows="2" cols="20" wrap="hard">{{element.hardwareKey}}</textarea> </td>
</ng-container>
<ng-container matColumnDef="Product" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>Product</strong></th>
<td mat-cell *matCellDef="let element"> {{element.product}} </td>
</ng-container>
<ng-container matColumnDef="MSAN" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>MSAN</strong></th>
<td mat-cell *matCellDef="let element"> {{element.msan}} </td>
</ng-container>
<ng-container matColumnDef="CPE" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>CPE</strong></th>
<td mat-cell *matCellDef="let element"> {{element.cpe}} </td>
</ng-container>
<ng-container matColumnDef="Service Connections" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-size:15px;" class="customtd"><strong>Service Connections</strong></th>
<td mat-cell *matCellDef="let element"> {{element.serviceConnections}} </td>
</ng-container>
<ng-container matColumnDef="License Key" margin-right:10px margin-left:5px>
<th mat-header-cell *matHeaderCellDef style="font-weight: bold;" style="font-size:15px;" class="customtd"><strong>License Key</strong></th>
<td mat-cell *matCellDef="let element"> <textarea rows="2" cols="20" wrap="hard" [readonly]="!editable">{{element.licenseKey}} </textarea></td>
</ng-container>
<ng-container matColumnDef="Actions" margin-right:10px margin-left:10px>
<th mat-header-cell *matHeaderCellDef style="font-weight: bold;" style="font-size:15px;" class="customtd"><strong>Actions</strong></th>
<td mat-cell *matCellDef="let element">
<button type="button" style="margin-left:5px" (click)="deleteLicense(element.id)">Delete</button>
<button type="button" style="margin-left:5px" (click)="openMxkLicenseDetailsDialog()">Update</button>
<button type="button" style="margin-left:5px" (click)="copyLicenseToClipboard(element.licenseKey)" class='btn btn-primary'>Copy License Key</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky:true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
</div>
</mat-dialog-content>
<br>
<br>
<br>
<strong>* Customer ID might not be present for some products.</strong>
<mat-dialog-actions align="end">
<button mat-button mat-raised-button mat-dialog-close cdkFocusInitial color="warn">Close</button>
</mat-dialog-actions>
Эта страница выглядит следующим образом:
Я хочу добавить кнопку поиска поверх этого всплывающего окна после заголовка. Я хочу уточнить этот список на основе идентификатора клиента, который имеет тип String. Однако первичный ключ — это идентификатор типа long, который не показан. Идентификатор — это @GeneratedValue свойства Auto в серверной части. Я попробовал следующий код, но не смог его правильно реализовать: https://stackblitz.com/edit/angular-search-filter?file=app/app.component.ts
Файл Component.ts для этого:
@Component({
selector: 'customer-list-dialog',
templateUrl: 'customer-list-dialog.html',
})
export class CustomerListDialog implements OnInit {
customerList : any;
isupdated = false;
displayedColumns: string[] = ['Customer ID', 'Hardware Key', 'Product', 'MSAN', 'CPE', 'Service Connections', 'License Key', 'Actions'];
constructor(
public dialogRef: MatDialogRef<AddProductDialog>,
private generateLicenseService: GeneratelicenseService,
@Inject(MAT_DIALOG_DATA) public data) {
}
ngOnInit() {
console.log("before the call : " this.customerList);
if(this.customerList === undefined) {
this.generateLicenseService.getCustomerDetails()
.subscribe((data) => {
this.customerList = data;
//console.log("after the call : " this.customerList);
});
}
}
И часть service.ts является:
getCustomerDetails() {
let headers = new HttpHeaders({
'Content-Type': 'application/json'
})
let options = {headers:headers, observer: 'response'};
let result : Observable<Object> = this.http.get(this.url '/customer/licenses',options);
return resu<
}
Ответ №1:
Если я правильно понимаю ваш вопрос, вам просто нужен простой текстовый фильтр, похожий на предоставленную вами ссылку?
Я бы предположил, что проще всего было бы изменить источник входных данных для вашего table
from customerList
to filteredCustomerList
.
В вашем компоненте, после получения списка клиентов и сохранения его как customerList
, также сохраните его как другую переменную filteredCustomerList
.
С добавлением вашего новейшего текстового поля для ввода поиска, например:
<input type="text" [(ngModel)]="filterText" (change)="onFilterChange()">
Затем вы можете изменить filteredCustomerList
содержимое, оставив оригинал customerList
в качестве источника данных, из которых нужно фильтровать, в противном случае нетронутым в фоновом режиме. Например:
public onFilterChange(): void {
if (!this.filterText || this.filterText.length === 0) {
this.filteredCustomerList = this.customerList;
return;
}
this.filteredCustomerList = this.customerList.filter(x => x.customerId.toString().includes(this.filterText));
}
Я подозреваю, что фильтр будет выглядеть примерно так, учитывая ваши опасения по поводу типов данных (строки и числовые типы). В конце концов, у numbers есть (честно говоря, у всего есть) .toString()
доступный метод, так что вы можете сравнить введенный текст фильтра с идентификаторами клиентов.
Это должно привести к желаемому результату изменения источника входных данных на основе введенного текста фильтра.
Редактировать: (change)
событие запускается только при снятии фокуса (щелчок по текстовому полю) или нажатии клавиши enter. Переключитесь на (keyup)
, если вы хотите фильтровать по мере ввода.
Краткий пример работы описанного механизма — StackBlitz
Комментарии:
1. хотя этот код не выдает никаких ошибок, ввод в поле поиска ничего не дает. Тем не менее, все значения поступают. Я изменил источник данных на filteredCustomerList и где я получаю данные, то есть this.CustomerList = data, я применил this.filteredCustomerList = data . переменная filterText задается как: filterText: строка; HTML-часть: <тип ввода=»текст» [(ngModel)]=»filterText» (изменить)=»onFilterChange()»><br><br>
2. есть какое-либо решение для этого?
3. Исправил мой ответ — предполагая, что событие изменения не подходит (поскольку вы предпочли бы, чтобы данные фильтровались по мере ввода, а не нажимали enter или что-то в этом роде).
4. Я допустил опечатку, вот почему она не работала. (change) работает, но попробую (keyup) тоже.