I'm hardliner in DRY (don't repeat yourself) concept. Right now I'm researching on Angular 2 API Reference and cant found the shorter way to create form :
import {Component, OnChanges, OnInit, SimpleChanges} from '@angular/core';
import {EmployeeSharedService} from "../employee-shared.service";
import {Employee} from "../employee";
import {EmployeeService} from "../employee.service";
import {FormControl, FormGroup} from "@angular/forms";
@Component({
selector: 'employee-detail',
providers: [ EmployeeService, CityService ],
templateUrl: './employee-detail.component.html',
styleUrls: ['./employee-detail.component.css']
})
export class EmployeeDetailComponent implements OnInit, OnChanges {
constructor(private employeeService:EmployeeService, private cityService:CityService, private employeeSharedService:EmployeeSharedService) { }
createForm() { // how to shorten this?
this.employeeForm = new FormGroup({
empId:new FormControl(),
firstName:new FormControl(),
lastName:new FormControl(),
gender:new FormControl(),
dateOfBirth:new FormControl(),
nationality:new FormControl(),
maritalStatus:new FormControl(),
phone:new FormControl(),
city:new FormControl(),
subDivision:new FormControl(),
status:new FormControl(),
suspendDate:new FormControl(),
hiredDate:new FormControl(),
grade:new FormControl(),
division:new FormControl(),
email:new FormControl()
});
}
setFormValue() { // see, this is can be shortened
this.employeeForm.setValue(this.selectedEmployee);
}
resetFormValue() { // see, this is can be shortened
this.employeeForm.reset(this.selectedEmployee);
}
nullifyFormValue() { // see, this is can be shortened
this.employeeForm.reset(new Employee());
}
}
Since I already have class Employee like this
export class Employee {
empId?:number;
firstName:string;
lastName:string;
gender:string;
dateOfBirth:Date;
nationality:string;
maritalStatus:string;
phone:string;
city: City;
subDivision:string;
status:string;
suspendDate:Date;
hiredDate:Date;
grade:string;
division:string;
email:string;
profilePicture?:string;
}
I can shorten reset form or set value. But how to shorten form creation?
Use the FormBuilder:
....
import { FormBuilder } from '@angular/forms';
.....
constructor(private employeeService:EmployeeService, private cityService:CityService, private employeeSharedService:EmployeeSharedService, private fb: FormBuilder) { }
createForm() { // how to shorten this?
this.employeeForm = this.fb.group({
empId: '',
firstName: '',
lastName:'',
.....
});
.....
Check out the docs to find out more.
I think the following could be what you are looking for.
Change to interfaces instead :) Creating an instance of that interface can be done like: employee: Employee: <Employee>{}, but that won't give the property keys you are looking for, so let's create a function that does that. The code samples below are shortened from yours. The function:
export function createEmployee(empId?:number,firstName?:string): Employee {
return {
empId,
firstName
}
}
import that function to your component and create an employee:
employee = createEmployee();
Now we have the properties we can iterate and create the form based on them:
ngOnInit() {
this.employeeForm = new FormGroup({});
this.setValues();
}
setValues() {
for(let key in this.employee) {
this.employeeForm.addControl(key, new FormControl(''))
}
}
Now we have all formfields, now you could of course write in your template all the different formControlName's longhand. Maybe you want to shorten that as well?
Create a pipe, that will iterate the formgroup:
@Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value)
}
}
And then the template let's use it:
<form [formGroup]="employeeForm">
<div *ngFor="let key of employeeForm.controls | keys">
<label>{{key}}: </label>
<input [formControlName]="key" />
</div>
</form>
But as said, you can also skip the iteration of the form and write them longhand :)
Here's a