#angular #angular10
#angular #angular10
Вопрос:
Я пытаюсь изменить ячейку таблицы на поле выбора по щелчку. Это то, что у меня есть до сих пор, но это кажется очень, очень неуклюжим. Я что-то упускаю в Angular2, что лучше удовлетворит мои потребности?
account-page.component.html
<table mat-table [dataSource]="dataSource | async" class="mat-elevation-z8">
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Name Column -->
<ng-container matColumnDef="payee">
<th mat-header-cell *matHeaderCellDef> Payee </th>
<td mat-cell *matCellDef="let transaction" (click)="onClick()">
<p [ngStyle]="{'display': show === false ? 'block' : 'none'}">{{transaction.payee.name}}</p>
<mat-select [ngStyle]="{'display': show === true ? 'block' : 'none'}">
<mat-option value="{{transaction.payee.name}}">{{transaction.payee.name}}</mat-option>
<mat-option>Test</mat-option>
</mat-select>
</td>
</ng-container>
</table>
учетная запись-page.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { TransactionsService } from 'src/app/core/services/transactions.service';
import { concatMap } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
@Component({
selector: 'app-account-page',
templateUrl: './account-page.component.html',
styleUrls: ['./account-page.component.css']
})
export class AccountPageComponent implements OnInit {
displayedColumns: string[] = ['payee'];
dataSource: Observable<any[]>;
show = false;
transactions$: Observable<any[]>;
constructor(private route: ActivatedRoute, private transactionService: TransactionsService) { }
ngOnInit(): void {
this.transactions$ = this.getTransactions();
this.dataSource = this.getTransactions();
}
getTransactions(): Observable<any[]> {
return this.route.params.pipe(concatMap(params => {
const accountId = params.id;
return this.transactionService.getTransactionsByAccountId(accountId);
}));
}
onClick() {
console.log('clicked');
this.show = !this.show;
}
}
Очевидно, что это MVP. Я бы хотел, чтобы столбец Name / payee отображался в виде текста в ячейке таблицы; однако при щелчке он динамически изменяется на a <select>/<mat-select>
. По сути, он просто изменяет свойства отображения <p>
<select>
элементов и и переключает отображение css. Спасибо!
Ответ №1:
Я не уверен, правильно ли я вас понял.
Если вы хотите изменить элементы, которые отображаются в вашей таблице динамически, я бы рекомендовал вам использовать структурные директивы, такие как *ngIf
(https://angular.io/guide/structural-directives ) вместо [ngStyle]='display'
атрибута.
Например, что-то вроде этого:
<table mat-table [dataSource]="dataSource | async" class="mat-elevation-z8">
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Name Column -->
<ng-container matColumnDef="payee">
<th mat-header-cell *matHeaderCellDef> Payee </th>
<td mat-cell *matCellDef="let transaction" (click)="onClick()">
<p *ngIf="!show">{{transaction.payee.name}}</p>
<mat-select *ngIf="show">
<mat-option value="{{transaction.payee.name}}">{{transaction.payee.name}}</mat-option>
<mat-option>Test</mat-option>
</mat-select>
</td>
</ng-container>
</table>
Если это не был ваш вопрос, то, пожалуйста, дайте мне более подробную информацию.
Комментарии:
1. Ого! Не знаю, как я это пропустил. Намного лучше и именно то, что я ищу. Спасибо!