Soy de línea dura en el concepto DRY (no te repitas). En este momento estoy investigando sobre la referencia de la API de Angular 2 y no puedo encontrar la forma más corta de crear un formulario:
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()); } }Como ya tengo clase Empleado como este
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; }Puedo acortar el formulario de reinicio o establecer el valor. Pero, ¿cómo acortar la creación de formularios?
Utilice el 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:'', ..... }); .....Consulte los documentos para obtener más información.
Creo que lo siguiente podría ser lo que estás buscando.
Cambie a interfaces en su lugar :) La creación de una instancia de esa interfaz se puede hacer como: employee: Employee: <Employee>{} , pero eso no le dará las claves de propiedad que está buscando, así que creemos una función que haga eso. Los ejemplos de código a continuación se acortan de los suyos. La función:
export function createEmployee(empId?:number,firstName?:string): Employee { return { empId, firstName } }importe esa función a su componente y cree un empleado:
employee = createEmployee();Ahora que tenemos las propiedades, podemos iterar y crear el formulario basado en ellas:
ngOnInit() { this.employeeForm = new FormGroup({}); this.setValues(); } setValues() { for(let key in this.employee) { this.employeeForm.addControl(key, new FormControl('')) } } Ahora que tenemos todos los campos de formulario, ahora puede, por supuesto, escribir en su plantilla todos los diferentes formControlName a mano. ¿Tal vez quieras acortar eso también?
Cree una tubería, que iterará el grupo de formularios:
@Pipe({ name: 'keys', pure: false }) export class KeysPipe implements PipeTransform { transform(value: any, args: any[] = null): any { return Object.keys(value) } }Y luego la plantilla vamos a usarla:
<form [formGroup]="employeeForm"> <div *ngFor="let key of employeeForm.controls | keys"> <label>{{key}}: </label> <input [formControlName]="key" /> </div> </form>Pero como se dijo, también puede omitir la iteración del formulario y escribirlos a mano :)
Aquí está un