我检查了许多帖子,但无法解决问题。我要做的是,当我单击“编辑”按钮时,出现一个对话框。我想用客户数据填充该表单。我可以获得行的数据,但无法用该数据填充表单。
我有服务,客户,客户和客户列表组件。我在客户组件中创建了表单。我要在客户列表组件中编辑一行,因为我在那里有客户列表。我可以使用customer.service中的populateForm(customer)函数将列表中的元素作为对象获得,但是我无法将其放入表单中。
customer.service.ts
@Injectable({
providedIn: 'root'
})
export class CustomerService {
formData : Customer;
list : Customer[];
readonly rootURL = 'http://localhost:8085/api/auth'
public _refreshNeeded$ = new Subject<void>();
constructor(
private http: HttpClient,
) { }
//PUT Request
getCustomers(): Observable<Array<Customer>> {
return this.http.get<CustomerModelResponse>(this.rootURL + '/customer',
{ headers: new HttpHeaders({ 'Content-Type': 'application/json' }) })
.pipe(map(x => x.content), catchError(this.handleError));
}
//Refresh after a successful POST Request
get refreshNeeded$() {
return this._refreshNeeded$;
}
//Insert Customer with POST Request
postCustomer(formData: Customer) {
return this.http
.post(this.rootURL + '/customer', formData)
.pipe(
tap(()=>{
this._refreshNeeded$.next();
})
);
}
//PUT Request
updateCustomer(formData : Customer){
return this.http.put(this.rootURL+'/customer/'+formData.id, formData);
}
//DELETE Request
deleteCustomer(id : number){
return this.http.delete<CustomerModelResponse>(this.rootURL+'/customer/'+id,
{headers : new HttpHeaders({'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT,DELETE',
'Access-Control-Allow-Credentials': 'true','Content-Type':'application/json',
'Authorization': '*',
'Access-Control-Allow-Headers': 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers'})})
.pipe(map(x => x.content), catchError(this.handleError));
}
//Handle Error (is not elaborated!!!)
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
//client error
console.log('client error: ' + error.error.message)
} else {
//backend error
console.log(`backend error: ${error.status} error: ${error.error}`)
}
return throwError('Hata oluştu')
}
//Trying to populate form for Edit button
/*populateForm(customer) {
this.formData = Object.assign({}, customer);
console.log('Row clicked: ', customer); "test" not really part of function, works correctly!
}*/
customer.component.ts
export class CustomerComponent implements OnInit {
constructor(
private service: CustomerService,
private notificationService: NotificationService,
public formBuilder: FormBuilder,
private ngZone: NgZone,
private router: Router,
public dialogRef: MatDialogRef<CustomerComponent>
) { }
customerForm: FormGroup;
ngOnInit() {
this.submitCustomerForm()
}
submitCustomerForm() {
this.customerForm = this.formBuilder.group({
id: new FormControl(null),
firstname: new FormControl('', Validators.required),
lastname: new FormControl('', Validators.required),
email: new FormControl('', Validators.email),
customerId: new FormControl(null, [Validators.required, Validators.minLength(5)])
});
}
//Creating new form after refreshing list
initializedFormGroup() {
this.customerForm.setValue({
id: null,
firstname: '',
lastname: '',
email: '',
customerId: null
})
}
onClear() {
this.customerForm.reset();
this.initializedFormGroup();
}
onSubmit() {
if (this.customerForm.valid) {
this.service.postCustomer(this.customerForm.value).subscribe(res => {
this.ngZone.run(() => this.router.navigateByUrl(''))
});
this.customerForm.reset();
this.initializedFormGroup();
this.notificationService.success('İşleminiz tamamlanmıştır')
this.onClose();
}
}
onClose() {
this.customerForm.reset();
this.initializedFormGroup();
this.dialogRef.close();
}
}
customer-list.component.ts
export class CustomerListComponent implements OnInit {
customerData: any = [];
dataSource: MatTableDataSource<Customer>;
@ViewChild(MatPaginator) paginator: MatPaginator;
displayedColumns: string[] = ['firstname', 'lastname', 'email', 'customerId', 'action'];
searchKey: string;
constructor(
private dialog: MatDialog,
public service: CustomerService,
) {
this.service._refreshNeeded$.subscribe(() => {
this.service.getCustomers().subscribe(data => {
this.customerData = data;
this.dataSource = new MatTableDataSource<Customer>(this.customerData);
setTimeout(() => {
this.dataSource.paginator = this.paginator;
}, 0);
})
})
this.service.getCustomers().subscribe(data => {
this.customerData = data;
this.dataSource = new MatTableDataSource<Customer>(this.customerData);
setTimeout(() => {
this.dataSource.paginator = this.paginator;
}, 0);
})
}
ngOnInit() { }
deleteCustomer(index: number, e) {
if (window.confirm('Are you sure?')) {
const data = this.dataSource.data;
data.splice((this.paginator.pageIndex * this.paginator.pageSize) + index, 1);
this.dataSource.data = data;
this.service.deleteCustomer(e.id).subscribe()
}
}
onSearchClear() {
this.searchKey = "";
this.applyFilter();
}
applyFilter() {
this.dataSource.filter = this.searchKey.trim().toLowerCase();
}
onEdit(element){
const dialogConfig = new MatDialogConfig();
this.service.populateForm(element);
dialogConfig.autoFocus = true;
dialogConfig.width = "30%";
this.dialog.open(CustomerComponent, dialogConfig);
}
}
customer-list.html编辑按钮部分
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef> </th>
<td mat-cell *matCellDef="let element; let i = index;">
<button mat-icon-button color="primary"(click)="onEdit(element)">
<mat-icon>edit</mat-icon>
</button>
</td>
</ng-container>
答案 0 :(得分:0)
除了在服务上调用方法(您也可以使用服务,但需要使用BehaviorSubject)之外,只需将data
设置为dialogConfig即可,如下所示:
customer-list.component.ts
onEdit(element) {
const dialogConfig = new MatDialogConfig();
// this.service.populateForm(element);
dialogConfig.autoFocus = true;
dialogConfig.width = "30%";
dialogConfig.data = element;
this.dialog.open(CustomerComponent, dialogConfig);
}
// or
onEdit(element) {
const dialogConfig = new MatDialogConfig();
// this.service.populateForm(element);
this.dialog.open(CustomerComponent, {
autoFocus : true,
data : element,
width : "30%",
});
}
customer.component.ts ,在客户组件中,您需要注入如下对话框数据
export class CustomerComponent {
...
constructor(
...,
@Inject(MAT_DIALOG_DATA) public data: DialogData, // `data` will contains the customer data and you can use it to `set` or `patch` the form
...
) {}
...
}