각도 재료의 기본 정렬 - 머리글 정렬
아래의 Angular Material 코드를 변경하여 데이터 테이블이 기본적으로 '이름' 열로 정렬되도록 하려면 어떻게 해야 합니까?화살표(현재 정렬 방향을 나타냄)가 표시되어야 합니다.
이것이 제가 이루고 싶은 목표입니다.
원본 코드:
<table matSort (matSortChange)="sortData($event)">
<tr>
<th mat-sort-header="name">Dessert (100g)</th>
<th mat-sort-header="calories">Calories</th>
<th mat-sort-header="fat">Fat (g)</th>
<th mat-sort-header="carbs">Carbs (g)</th>
<th mat-sort-header="protein">Protein (g)</th>
</tr>
<tr *ngFor="let dessert of sortedData">
<td>{{dessert.name}}</td>
<td>{{dessert.calories}}</td>
<td>{{dessert.fat}}</td>
<td>{{dessert.carbs}}</td>
<td>{{dessert.protein}}</td>
</tr>
</table>
이와 같은 것을 시도해 보았지만 작동하지 않습니다(화살표가 표시되지 않고 정렬되지 않음
<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortStart="asc" matSortDisableClear>
플런커 링크입니다.
당신은 착각하고 있습니다.matSortStart위해서matSortDirection.
사용해 보십시오.
<table matSort (matSortChange)="sortData($event)" matSortActive="name" matSortDirection="asc" matSortDisableClear>
https://stackblitz.com/edit/angular-defaultsort?file=src/app/sort-overview-example.html
matSortStart정렬할 때 사용되는 주기를 반전시키는 데 사용할 수 있습니다(예: 사용자가 정렬할 때 클릭하면 asc가 아닌 desc에서 시작됨).
편집: 업데이트된 예제를 제공해 주신 Ben에게 감사드립니다.
하여 프로그래밍 할 수 .sort(Sortable)데이터 원본의 메서드입니다.당신이 가지고 있다고 가정할 때dataSource데이터 원본의 구성 요소 속성:
// to put next to the class fields of the component
@ViewChild(MatSort) sort: MatSort
// to put where you want the sort to be programmatically triggered, for example inside ngOnInit
this.sort.sort(({ id: 'name', start: 'asc'}) as MatSortable);
this.dataSource.sort = this.sort;
@ViewChild(MatSort) sort: MatSort;
this.dataSource.sort = this.sort;
const sortState: Sort = {active: 'name', direction: 'desc'};
this.sort.active = sortState.active;
this.sort.direction = sortState.direction;
this.sort.sortChange.emit(sortState);
작동해야 합니다. 데모
그리고 정렬 방향 화살표를 표시하려면 다음 CSS를 추가합니다(해결 방법).
th.mat-header-cell .mat-sort-header-container.mat-sort-header-sorted .mat-sort-header-arrow {
opacity: 1 !important;
transform: translateY(0) !important;
}
재료 업데이트(v7.3에서 테스트):
@ViewChild(MatSort) matSort: MatSort;
private someMethod(): void {
this.matSort.sort({ id: 'columnName', start: 'asc', disableClear: false });
}
된 이작 됩니다.mat-sort-header 방법이 의
매트 테이블 정렬 속성을 구성 요소 변수에 바인딩할 수도 있습니다.
@Andrew Seguin이 말했듯이:
<table matSort matSortActive="name" matSortDirection="asc">
이 방법은 기본 정렬이 무엇인지 알고 있는 경우 기본 정렬을 설정하는 데 적합합니다.
다른 곳에서 정렬하는 경우(쿼리 문자열 매개변수에서 정렬하는 경우) 다음과 같이 수행할 수도 있습니다(여기서 정렬 화살표가 완벽하게 작동합니다).
sortDirection: 'name', // this can be changed or filled in any time
sortProperty: 'asc',
<mat-table matSort [matSortActive]="sortProperty" [matSortDirection]="sortDirection">
동작에 영향을 미치는 몇 가지 요인이 있습니다.대부분 MatTableDataSource를 사용하는 것과 수동으로 만든 DataSource 파생 제품을 사용하는 것입니다.따라서 다양한 솔루션이 어떤 경우에는 효과가 있을 수 있고 다른 경우에는 그렇지 않을 수 있습니다.
어쨌든, 깃허브에서 잘 다뤄진 오래된 버그입니다.각진 팀의 관심을 끌 수 있도록 깃허브 이슈에 투표해주시기 바랍니다.
GitHub 스레드(링크)에 게시된 가장 내구성 있는 솔루션은 정렬 순서를 적용할 때 다음 방법을 호출하는 것입니다.
public setSort(id: string, start?: 'asc' | 'desc') {
start = start || 'asc';
const matSort = this.dataSource.sort;
const toState = 'active';
const disableClear = false;
//reset state so that start is the first sort direction that you will see
matSort.sort({ id: null, start, disableClear });
matSort.sort({ id, start, disableClear });
//ugly hack
(matSort.sortables.get(id) as MatSortHeader)._setAnimationTransitionState({ toState });
}
제 경우 matColumDefid와 mat-cell var가 다르기 때문에 정렬이 작동하지 않았습니다.
<ng-container matColumnDef="firstName">
<th mat-header-cell *matHeaderCellDef mat-sort-header class="mat-table-header">First Name</th>
<td mat-cell *matCellDef="let item"> {{ item.name}}</td>
</ng-container>
matColumnDef="firstName"을 matColumnDef="name"으로 변경한 후(item.name 과 동일)
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef mat-sort-header class="mat-table-header">First Name</th>
<td mat-cell *matCellDef="let item"> {{ item.name}}</td>
</ng-container>
저한테는 잘 됩니다.
@Andrew Seguin(첫 번째 및 수락된 답변)의 답변은 저에게 시각적 트릭을 주었지만, 테이블을 분류하지는 않았습니다.
제 해결책은 @Andrew Seguin에서 제공하는 html 코드를 사용하여 sortData(sort:Sort) 메서드를 직접 호출하는 것입니다. 그런데 어떻게 해야 하나요?설명서에 명시된 대로 ,,Sort'는 활성 및 방향이라는 두 가지 속성을 가진 인터페이스이며 인터페이스는 다음과 같이 보여야 합니다.
export interface Sort {
active:string //The id/name of the column being sorted
direction:string //asc or dsc depending on the use case (The sort direction)
}
따라서 ngOnInit에서 sortData(sort:Sort) 메서드를 다음과 같이 호출하는 것이 요령입니다.
ngOnInit(){
//Do some nitialization
this.sortData({active:'name', direction:'asc'});
}
sortData(sort: Sort) {
//Your sorting algorithm (see examples in documentation, link above and at the bottom)
}
HTML 코드는 승인된 답변과 같습니다;-) 이것이 누구에게나 도움이 되기를 바랍니다, 알렉스.
페이지의 초기 페이지에서 이름과 방향에 강제로 정렬 기능을 호출하려고 시도한 적이 있습니까?
ngOnInit() {
let defSort: Sort = {};
defSort.direction = 'asc';
defSort.active = 'name';
this.sortData(defSort);
}
로드 시 기본 정렬을 수행해야 했습니다.
const matSort = { id: defaultSort.name } as MatSortable;
this.sort.direction = defaultSort.sort === 'asc' ? '' : defaultSort.sort === 'desc' ? 'asc' : 'desc' as SortDirection;
this.sort.sort(matSort);
정렬을 프로그래밍 방식으로 추가하려면 CSS에 이것을 추가합니다.
::ng-deep.mat-header-cell .mat-sort-header-container.mat-sort-header-sorted .mat-sort-header-arrow { opacity: 1 !important; }
다음 코드를 추가할 수 있습니다.
ngAfterViewInit{
this.sort.disableClear = true;
this.sort.sort({disableClear: true, id:sortEnabledColumns.id,start:'asc'})
}
첫 번째 줄이 없으면 세 번째 클릭 시 기본 숨기기 상태로 이동합니다.
I found this in Github, works fine for me
@ViewChild(MatSort) sort: MatSort;
//reset state so that start is the first sort direction that you will see
this.sort.sort({ id: null, start: 'desc', disableClear: true });
this.sort.sort({ id: 'FieldNameToSort', start: 'asc', disableClear: true });
this.sort.sortChange.emit(this.sort);
(this.sort.sortables.get('FieldNameToSort') as MatSortHeader)._setAnimationTransitionState({ toState: 'active' });
언급URL : https://stackoverflow.com/questions/46743115/default-sorting-in-angular-material-sort-header
'programing' 카테고리의 다른 글
| VS Code Azure 계정 확장을 통해 계정을 전환하는 방법 (0) | 2023.05.14 |
|---|---|
| 장고: 작업 오류 해당 테이블 없음 (0) | 2023.05.14 |
| 문자열을 별도의 변수로 분할 (0) | 2023.05.14 |
| MongoDB 캐시 시스템 이해 (0) | 2023.05.14 |
| "ViewController라는 클래스에 대한 정보를 찾을 수 없습니다." (0) | 2023.05.14 |
