编辑和更新功能在 angular 代码中不起作用
Edit and update function is not working in angular code
我在编辑表格时遇到问题。单击编辑按钮时我无法获取表单值。只有值在控制台中可见。并且更新按钮也不起作用。
prepaid.component.html
<div><button style="margin:10px 0 0 50px;"mat-raised-button color="warn" routerLink="/addPlan"><mat-icon >add_circle_outline</mat-icon>Add Plan</button>
</div>
<div class="container" id="main-container">
<div style="margin-top:10px">
<mat-form-field appearance="standard">
<mat-label>Search</mat-label>
<input matInput placeholder="Ex." #input>
</mat-form-field>
<div ngFor="let row of plan" class="mat-elevation-z8">
<table [dataSource]="dataSource" mat-table matSort>
<!-- ID Column -->
<ng-container matColumnDef="planType">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Type </th>
<td mat-cell *matCellDef="let row"> {{row?.planType}} </td>
</ng-container>
<!-- Progress Column -->
<ng-container matColumnDef="planName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> PlanName </th>
<td mat-cell *matCellDef="let row"> {{row?.planName}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="planPrice">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Price </th>
<td mat-cell *matCellDef="let row"> Rs.{{row?.planPrice}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planDescription">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Description </th>
<td mat-cell *matCellDef="let row"> {{row?.planDescription}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planOffers">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Offers </th>
<td mat-cell *matCellDef="let row"> {{row?.planOffers}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planValidity">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Validity </th>
<td mat-cell *matCellDef="let row"> {{row?.planValidity}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Action </th>
<td mat-cell *matCellDef="let row">
<a mat-icon-button color="primary" routerLink="/editPlan/{{row.id}}" (click)="editPlan(row,row.id)">
<mat-icon>edit</mat-icon>
</a>
<button mat-icon-button color="warn" (click)="deletePlan(row.id)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Row shown when there is no matching data. -->
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
</tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 25, 100]" aria-label="Select page of users"></mat-paginator>
</div>
</div>
</div>
prepaid.component.ts
import { Component, Input, OnInit,ViewChild } from '@angular/core';
import { AddPlanComponent } from '../add-plan/add-plan.component';
import { AdminApiService } from '../services/admin-api.service';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import { Plan } from 'src/app/plan';
import {MatDialog} from '@angular/material/dialog';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-prepaid',
templateUrl: './prepaid.component.html',
styleUrls: ['./prepaid.component.css']
})
export class PrepaidComponent implements OnInit {
plan!: Plan[];
plandata!: Plan;
editPlanData!:FormGroup;
displayedColumns: string[] = ['planType', 'planName', 'planPrice','planDescription','planOffers','planValidity','action'];
dataSource!: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(private formBuilder:FormBuilder,public dialog: MatDialog,private api:AdminApiService,private route:ActivatedRoute) {}
ngOnInit(): void{
this.getPrePlan();
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan[])=>{
this.plan=response;
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}
deletePlan(id:number){
this.api.deletePlan(id)
.subscribe({
next:(res)=>{
alert("Plan deleted successfully");
this.getPrePlan();
},
error:()=>{
alert("error on deleting");
}
});
}
editPlan(response:Plan,id:number){
/*this.editPlanData.controls['id'].setValue(response.id);
this.editPlanData.controls['planName'].setValue(response.planName);
this.editPlanData.controls['planPrice'].setValue(response.planPrice);
this.editPlanData.controls['planType'].setValue(response.planType);
this.editPlanData.controls['planOffers'].setValue(response.planOffers);
this.editPlanData.controls['planDescription'].setValue(response.planDescription);
this.editPlanData.controls['planValidity'].setValue(response.planValidity);*/
console.log(response);
}
}
编辑-plan.component.html
<div id="Editplan" class="example-container">
<form ngFor="let editPlan of plan" [formGroup]="editPlanData">
<mat-form-field hidden appearance="outline">
<mat-label hidden>id</mat-label>
<input hidden matInput placeholder="Enter plan name" id="id" formControlName="id">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan name</mat-label>
<input matInput placeholder="Enter plan name" id="planName" formControlName="planName" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter the plan price</mat-label>
<input matInput placeholder="Enter the plan price" type="number" id="planPrice" formControlName="planPrice" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan type</mat-label>
<mat-select id="planType" formControlName="planType" required>
<mat-option value="Prepaid">Prepaid</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter the offer for the plan</mat-label>
<mat-select id="planOffers" formControlName="planOffers" required>
<mat-option value="Netflix">Netflix</mat-option>
<mat-option value="Amazon">Amazon</mat-option>
<mat-option value="Hotstar">Hotstar</mat-option>
<mat-option value="No Offer">None</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan validity</mat-label>
<input matInput placeholder="Enter plan validity" id="planValidity" formControlName="planValidity" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan description</mat-label>
<textarea matInput placeholder="Enter plan description" id="planDescription" formControlName="planDescription" required></textarea>
</mat-form-field>
</form>
<div mat-dialog-action [align]="'end'">
<button class="save-btn" id="plan-details" mat-raised-button color="warn">Update</button>
</div>
</div>
编辑-plan.component.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 { Plan } from '../plan';
import { AdminApiService } from '../services/admin-api.service';
import { NgForm } from '@angular/forms';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-edit-plan',
templateUrl: './edit-plan.component.html',
styleUrls: ['./edit-plan.component.css']
})
export class EditPlanComponent implements OnInit {
public plan!: Plan[];
dataSource!: MatTableDataSource<any>;
public editPlan!: Plan;
editPlanData!:FormGroup;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(private formBuilder:FormBuilder,private api: AdminApiService) { }
ngOnInit(): void {
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
/*this.editPlanData.controls['id'].setValue(this.editPlan.id);
this.editPlanData.controls['planName'].setValue(this.editPlan.planName);
this.editPlanData.controls['planPrice'].setValue(this.editPlan.planPrice);
this.editPlanData.controls['planType'].setValue(this.editPlan.planType);
this.editPlanData.controls['planOffers'].setValue(this.editPlan.planOffers);
this.editPlanData.controls['planDescription'].setValue(this.editPlan.planDescription);
this.editPlanData.controls['planValidity'].setValue(this.editPlan.planValidity);*/
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan[])=>{
this.plan=response;
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}
public OnUpdatePlan(editForm:NgForm): void{
this.api.updatePlan(this.editPlan.id,editForm.value)
.subscribe({
next:(response:Plan)=>{
console.log(response);
this.getPrePlan();
},
error:()=>{
alert("Error while adding records")
}
});
}
}
service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Plan } from 'src/app/plan'
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AdminApiService {
private apiServerUrl=environment.apiBaseUrl;
constructor(private http : HttpClient) { }
public getPlans(): Observable<Plan[]> {
return this.http.get<Plan[]>(`${this.apiServerUrl}/prepaid-plan/all`);
}
public addPlan(plan: Plan): Observable<Plan> {
return this.http.post<Plan>(`${this.apiServerUrl}/prepaid-plan/add`, plan);
}
updatePlan(planId:number,plan:Plan): Observable<Plan>{
return this.http.put<Plan>(`${this.apiServerUrl}/prepaid-plan/update/`+planId,plan);
}
public deletePlan(planId: number): Observable<void> {
return this.http.delete<void>(`${this.apiServerUrl}/prepaid-plan/delete/${planId}`);
}
}
plan.ts
export interface Plan {
id: number;
planName: string;
planType: string;
planPrice: string;
planOffers: string;
planDescription: string;
planValidity: string;
}
输出一个
点击编辑按钮时的输出
如何获取编辑表单中的值?
你有两种方法:
你可以试试这个,
你没有调用 setValue
this.editPlanData.setValue(response);
ngOnInit(): void {
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
this.getPrePlan();
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan)=>{
this.plan=response;
this.editPlanData.setValue(response);
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}
我在编辑表格时遇到问题。单击编辑按钮时我无法获取表单值。只有值在控制台中可见。并且更新按钮也不起作用。
prepaid.component.html
<div><button style="margin:10px 0 0 50px;"mat-raised-button color="warn" routerLink="/addPlan"><mat-icon >add_circle_outline</mat-icon>Add Plan</button>
</div>
<div class="container" id="main-container">
<div style="margin-top:10px">
<mat-form-field appearance="standard">
<mat-label>Search</mat-label>
<input matInput placeholder="Ex." #input>
</mat-form-field>
<div ngFor="let row of plan" class="mat-elevation-z8">
<table [dataSource]="dataSource" mat-table matSort>
<!-- ID Column -->
<ng-container matColumnDef="planType">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Type </th>
<td mat-cell *matCellDef="let row"> {{row?.planType}} </td>
</ng-container>
<!-- Progress Column -->
<ng-container matColumnDef="planName">
<th mat-header-cell *matHeaderCellDef mat-sort-header> PlanName </th>
<td mat-cell *matCellDef="let row"> {{row?.planName}} </td>
</ng-container>
<!-- Name Column -->
<ng-container matColumnDef="planPrice">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Price </th>
<td mat-cell *matCellDef="let row"> Rs.{{row?.planPrice}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planDescription">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Description </th>
<td mat-cell *matCellDef="let row"> {{row?.planDescription}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planOffers">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Offers </th>
<td mat-cell *matCellDef="let row"> {{row?.planOffers}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="planValidity">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Validity </th>
<td mat-cell *matCellDef="let row"> {{row?.planValidity}} </td>
</ng-container>
<!-- Fruit Column -->
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef mat-sort-header> Action </th>
<td mat-cell *matCellDef="let row">
<a mat-icon-button color="primary" routerLink="/editPlan/{{row.id}}" (click)="editPlan(row,row.id)">
<mat-icon>edit</mat-icon>
</a>
<button mat-icon-button color="warn" (click)="deletePlan(row.id)">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
<!-- Row shown when there is no matching data. -->
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" colspan="4">No data matching the filter "{{input.value}}"</td>
</tr>
</table>
<mat-paginator [pageSizeOptions]="[10, 25, 100]" aria-label="Select page of users"></mat-paginator>
</div>
</div>
</div>
prepaid.component.ts
import { Component, Input, OnInit,ViewChild } from '@angular/core';
import { AddPlanComponent } from '../add-plan/add-plan.component';
import { AdminApiService } from '../services/admin-api.service';
import {MatTableDataSource} from '@angular/material/table';
import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import { Plan } from 'src/app/plan';
import {MatDialog} from '@angular/material/dialog';
import { HttpErrorResponse } from '@angular/common/http';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-prepaid',
templateUrl: './prepaid.component.html',
styleUrls: ['./prepaid.component.css']
})
export class PrepaidComponent implements OnInit {
plan!: Plan[];
plandata!: Plan;
editPlanData!:FormGroup;
displayedColumns: string[] = ['planType', 'planName', 'planPrice','planDescription','planOffers','planValidity','action'];
dataSource!: MatTableDataSource<any>;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(private formBuilder:FormBuilder,public dialog: MatDialog,private api:AdminApiService,private route:ActivatedRoute) {}
ngOnInit(): void{
this.getPrePlan();
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan[])=>{
this.plan=response;
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}
deletePlan(id:number){
this.api.deletePlan(id)
.subscribe({
next:(res)=>{
alert("Plan deleted successfully");
this.getPrePlan();
},
error:()=>{
alert("error on deleting");
}
});
}
editPlan(response:Plan,id:number){
/*this.editPlanData.controls['id'].setValue(response.id);
this.editPlanData.controls['planName'].setValue(response.planName);
this.editPlanData.controls['planPrice'].setValue(response.planPrice);
this.editPlanData.controls['planType'].setValue(response.planType);
this.editPlanData.controls['planOffers'].setValue(response.planOffers);
this.editPlanData.controls['planDescription'].setValue(response.planDescription);
this.editPlanData.controls['planValidity'].setValue(response.planValidity);*/
console.log(response);
}
}
编辑-plan.component.html
<div id="Editplan" class="example-container">
<form ngFor="let editPlan of plan" [formGroup]="editPlanData">
<mat-form-field hidden appearance="outline">
<mat-label hidden>id</mat-label>
<input hidden matInput placeholder="Enter plan name" id="id" formControlName="id">
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan name</mat-label>
<input matInput placeholder="Enter plan name" id="planName" formControlName="planName" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter the plan price</mat-label>
<input matInput placeholder="Enter the plan price" type="number" id="planPrice" formControlName="planPrice" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan type</mat-label>
<mat-select id="planType" formControlName="planType" required>
<mat-option value="Prepaid">Prepaid</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter the offer for the plan</mat-label>
<mat-select id="planOffers" formControlName="planOffers" required>
<mat-option value="Netflix">Netflix</mat-option>
<mat-option value="Amazon">Amazon</mat-option>
<mat-option value="Hotstar">Hotstar</mat-option>
<mat-option value="No Offer">None</mat-option>
</mat-select>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan validity</mat-label>
<input matInput placeholder="Enter plan validity" id="planValidity" formControlName="planValidity" required>
</mat-form-field>
<mat-form-field appearance="outline">
<mat-label>Enter plan description</mat-label>
<textarea matInput placeholder="Enter plan description" id="planDescription" formControlName="planDescription" required></textarea>
</mat-form-field>
</form>
<div mat-dialog-action [align]="'end'">
<button class="save-btn" id="plan-details" mat-raised-button color="warn">Update</button>
</div>
</div>
编辑-plan.component.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 { Plan } from '../plan';
import { AdminApiService } from '../services/admin-api.service';
import { NgForm } from '@angular/forms';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
@Component({
selector: 'app-edit-plan',
templateUrl: './edit-plan.component.html',
styleUrls: ['./edit-plan.component.css']
})
export class EditPlanComponent implements OnInit {
public plan!: Plan[];
dataSource!: MatTableDataSource<any>;
public editPlan!: Plan;
editPlanData!:FormGroup;
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
constructor(private formBuilder:FormBuilder,private api: AdminApiService) { }
ngOnInit(): void {
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
/*this.editPlanData.controls['id'].setValue(this.editPlan.id);
this.editPlanData.controls['planName'].setValue(this.editPlan.planName);
this.editPlanData.controls['planPrice'].setValue(this.editPlan.planPrice);
this.editPlanData.controls['planType'].setValue(this.editPlan.planType);
this.editPlanData.controls['planOffers'].setValue(this.editPlan.planOffers);
this.editPlanData.controls['planDescription'].setValue(this.editPlan.planDescription);
this.editPlanData.controls['planValidity'].setValue(this.editPlan.planValidity);*/
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan[])=>{
this.plan=response;
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}
public OnUpdatePlan(editForm:NgForm): void{
this.api.updatePlan(this.editPlan.id,editForm.value)
.subscribe({
next:(response:Plan)=>{
console.log(response);
this.getPrePlan();
},
error:()=>{
alert("Error while adding records")
}
});
}
}
service.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';
import { Plan } from 'src/app/plan'
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class AdminApiService {
private apiServerUrl=environment.apiBaseUrl;
constructor(private http : HttpClient) { }
public getPlans(): Observable<Plan[]> {
return this.http.get<Plan[]>(`${this.apiServerUrl}/prepaid-plan/all`);
}
public addPlan(plan: Plan): Observable<Plan> {
return this.http.post<Plan>(`${this.apiServerUrl}/prepaid-plan/add`, plan);
}
updatePlan(planId:number,plan:Plan): Observable<Plan>{
return this.http.put<Plan>(`${this.apiServerUrl}/prepaid-plan/update/`+planId,plan);
}
public deletePlan(planId: number): Observable<void> {
return this.http.delete<void>(`${this.apiServerUrl}/prepaid-plan/delete/${planId}`);
}
}
plan.ts
export interface Plan {
id: number;
planName: string;
planType: string;
planPrice: string;
planOffers: string;
planDescription: string;
planValidity: string;
}
输出一个
点击编辑按钮时的输出
如何获取编辑表单中的值?
你有两种方法:
你可以试试这个, 你没有调用 setValue
this.editPlanData.setValue(response);
ngOnInit(): void {
this.editPlanData=this.formBuilder.group({
id:[''],
planName:[''],
planType:[''],
planPrice:[''],
planOffers:[''],
planValidity:[''],
planDescription:['']
});
this.getPrePlan();
}
public getPrePlan():void{
this.api.getPlans()
.subscribe({
next:(response:Plan)=>{
this.plan=response;
this.editPlanData.setValue(response);
this.dataSource=new MatTableDataSource(response);
this.dataSource.paginator=this.paginator;
this.dataSource.sort=this.sort;
},
error:()=>{
alert("Error while fetching records")
}
});
}