我想弄清楚如何使用角度材料表中的数据填充反应形式。我可以在模板驱动表中使用:
populateForm(rd: Shift) {
this.shiftsService.formData = Object.assign({}, rd)
}
但我无法实现相同的知识来填充反应式表单。
这是一个工作示例: https://angular-ivy-uwuzdg.stackblitz.io
表格是这样的:
<mat-card>
<div fxLayoutAlign="start center">
<mat-form-field fxFlex="30%">
<mat-label>Search Shift</mat-label>
<input matInput type="text" (keyup)="doFilter($event.target.value)" placerholder="filter">
</mat-form-field>
</div>
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="start"> <!--grouping mechanism -->
<th mat-header-cell *matHeaderCellDef mat-sort-header>Start</th> <!--structural directive-->
<td mat-cell *matCellDef="let element" (click)="populateForm(element)">{{ element.start | date }}</td>
</ng-container>
这是table.ts
export class ShiftsListComponent implements OnInit, AfterViewInit {
displayedColumns = ['start', 'end', 'category', 'location', 'money', 'button'] // for the dataTable, names have to match "matcolumndef" on view
dataSource = new MatTableDataSource<Shift>();
@ViewChild(MatSort) sort: MatSort;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(public shiftsService: ShiftsService) { }
ngOnInit() {
this.getAllShifts();
}
ngAfterViewInit() {
this.dataSource.sort = this.sort;
this.dataSource.paginator = this.paginator;
}
doFilter(filterValue: string) {
this.dataSource.filter = filterValue.trim().toLowerCase();
}
// hideValues () {
// this.dataSource.filteredData()
// }
populateForm(rd: Shift) {
console.log("mr. populate")
this.shiftsService.formData = Object.assign({}, rd)
}
public getAllShifts() {
let resp = this.shiftsService.getShifts();
console.log(resp)
resp.then(shifts => this.dataSource.data = shifts as Shift[]);
}
onDelete(id) {
if (confirm('Are you sure?')) {
this.shiftsService.deleteShiftDetail(id)
.subscribe(
res => {
this.shiftsService.getShifts()
.then(shifts => this.dataSource.data = shifts as Shift[]);
},
err => {
console.log(err);
})
}
}
}
这是表格
<form
fxLayout="row"
fxLayoutAlign="center center"
fxLayoutGap="10px"
[formGroup]="shiftsForm"
(ngSubmit)="onSubmit()"
>
<mat-form-field>
<input matInput [ngxMatDatetimePicker]="pickerStart" placeholder="Choose a date" formControlName="dateStart"
[disabled]="disabled">
<mat-datepicker-toggle matSuffix [for]="pickerStart"></mat-datepicker-toggle>
<ngx-mat-datetime-picker #pickerStart [showSpinners]="showSpinners"
[stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond" >
</ngx-mat-datetime-picker>
</mat-form-field>
<mat-form-field>
<input matInput [ngxMatDatetimePicker]="pickerEnd" placeholder="Choose a date" formControlName="dateEnd"
[disabled]="disabled">
<mat-datepicker-toggle matSuffix [for]="pickerEnd"></mat-datepicker-toggle>
<ngx-mat-datetime-picker #pickerEnd [showSpinners]="showSpinners"
[stepHour]="stepHour" [stepMinute]="stepMinute" [stepSecond]="stepSecond">
</ngx-mat-datetime-picker>
</mat-form-field>
这是form.ts
export class ShiftsFormComponent implements OnInit {
public disabled = false;
public showSpinners = true;
public stepHour = 1;
public stepMinute = 1;
public stepSecond = 1;
public options = [
{ value: true, label: 'True' },
{ value: false, label: 'False' }
];
public listColors = ['primary', 'accent', 'warn'];
public stepHours = [1, 2, 3, 4, 5];
public stepMinutes = [1, 5, 10, 15, 20, 25];
public stepSeconds = [1, 5, 10, 15, 20, 25];
shiftsForm: FormGroup;
constructor(private shiftsService: ShiftsService) { }
ngOnInit(): void {
this.shiftsForm = new FormGroup ({
category: new FormControl(""),
location: new FormControl(""),
money: new FormControl(""),
dateStart : new FormControl(new Date("")),
dateEnd : new FormControl(new Date(""))
});
console.log(this.shiftsService.getShifts());
}
onSubmit() {
console.log(this.shiftsForm)
this.shiftsService.postShiftDetail({
start: this.shiftsForm.value.dateStart,
end: this.shiftsForm.value.dateEnd,
money: this.shiftsForm.value.money,
categoryId: this.shiftsForm.value.category,
locationId: this.shiftsForm.value.location,
}).subscribe(
res => {
console.log("Yay")
},
err => {
console.log(err);
});;
}
}
这是服务
@Injectable({
providedIn: 'root'
})
export class ShiftsService {
formData: Shift;
dataSource = new MatTableDataSource<Shift>();
// categoryFormData: Category;
// readonly rootURL = 'https://cappuccinobudget.azurewebsites.net/api';
readonly rootURL = 'https://localhost:5001/api';
private fbSubs: Subscription[] = [];
constructor(private http: HttpClient) { }
postShiftDetail(formData) {
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}
return this.http.post(this.rootURL + '/shifts', formData, httpOptions)
}
putShiftDetail() {
return this.http.put(
this.rootURL + '/shifts/' + this.formData.id,
this.formData)
}
deleteShiftDetail(id) {
return this.http.delete(
this.rootURL + '/shifts/' + id,
)
}
public getShifts() {
return this.http.get(this.rootURL + '/shifts').toPromise()
.then(shifts => this.dataSource.data = shifts as Shift[]);
}