#angular #forms #angular-material #angular-reactive-forms #angular-material-table
Вопрос:
В настоящее время я пытаюсь создавать формы в таблицах угловых материалов. В ngAfterViewInit() я подписался на observable, чтобы получить пользовательские данные, и использовал эти данные для создания новой формгруппы, прежде чем отправлять ее в FormsArray. Затем я использовал FormsArray в качестве источника данных для таблицы.
Несмотря на то, что при разбиении на страницы внизу отображается результат 2, в таблице не отображаются никакие формы.
Я не уверен, почему это происходит, и мне нужна помощь в этом вопросе.
user-profile.component.html
<form [formGroup]="form" autocomplete="off">
<div formArrayName="userInfo">
<table mat-table [dataSource]="userInfo.controls" matSort class="mat-elevation-z8">
<ng-container matColumnDef="Username">
<th mat-header-cell *matHeaderCellDef mat-sort-header>Username</th>
<td mat-cell *matCellDef="let element; let i = index">
<mat-form-field [formGroup]="element">
<input formControlName="username" matInput placeholder="Username" />
</mat-form-field>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
<mat-paginator [pageSize]="[5]"></mat-paginator>
</div>
профиль пользователя.компонент.ts
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatSort } from '@angular/material/sort';
import { MatTableDataSource } from '@angular/material/table';
import { UserService } from '../../service/user.service';
import { merge, Observable, of as observableOf } from 'rxjs';
import { catchError, first, map, startWith, switchMap } from 'rxjs/operators';
import { FormBuilder, FormGroup, ReactiveFormsModule, FormArray, Validators } from '@angular/forms';
@Component({
selector: 'app-user-profile',
templateUrl: './user-profile.component.html',
styleUrls: ['./user-profile.component.css']
})
export class UserProfileComponent implements OnInit {
displayedColumns: string[] = ['Username'];
dataSource: MatTableDataSource<any> = new MatTableDataSource();
form: FormGroup;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor(private userService: UserService, private fb: FormBuilder) {
this.form = this.fb.group({
userInfo: this.fb.array([])
});
}
ngOnInit(): void { }
ngAfterViewInit() {
this.userService.getAllUsers().subscribe(res => {
console.log(res);
this.dataSource.data = [...res.body];
for(let i=0; i< this.dataSource.data.length; i ){
this.userInfo.push(this.newUser(this.dataSource.data[i]))
console.log(i);
}
});
this.sort.sortChange.subscribe(() => this.paginator.pageIndex = 0);
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
applyFilter(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
if (this.dataSource.paginator) {
this.dataSource.paginator.firstPage();
}
}
get userInfo(): FormArray {
return this.form.get("userInfo") as FormArray;
}
newUser(userInfo): FormGroup{
return this.fb.group({
username: userInfo.ap_username
});
}
save() {
console.log(this.userInfo.controls);
}
}