So instead of declaring the FormGroup and FormControl instances manually:
export class CruiseShipComponent extends Vadacl implements OnInit { cruiseShip: CruiseShip; shipForm: FormGroup; ngOnInit() { this.cruiseShip = new CruiseShip(); this.shipForm = new FormGroup({ 'name': new FormControl( this.cruiseShip.name, this.applyRules( this.cruiseShip, 'name' ) ), 'cruiseLine': new FormControl( this.cruiseShip.cruiseLine, this.applyRules( this.cruiseShip, 'cruiseLine' ) ), 'yearBuilt': new FormControl( this.cruiseShip.yearBuilt, this.applyRules( this.cruiseShip, 'yearBuilt' ) ) }); }
...you can simply invoke generateForm() with the data object:
... ngOnInit() { this.cruiseShip = new CruiseShip(); this.shipForm = this.generateForm( this.cruiseShip ); }
generateForm() also accepts a second arguments: a "mods" object that allows you to customize the FormGroup returned by the method. The possible modification properties are:
- exclude: an array of data object properties you don't want to create a FormControl for.
- only: an array of the only data object properties you want to create FormControls for (overrides the "exclude" property if you mistakenly use both).
- rename: an object literal for remapping a data object property name (key) to a different FormControl name (value).
- validations: an object literal of additional validations to apply to particular data object properties.
An example of using the mods argument:
this.shipForm = this.generateForm( this.cruiseShip, { exclude: [ 'yearBuilt' ], rename: { cruiseLine: 'company' }, validations: { name: { maxLength: { maxLength: 100, message: 'Ship name cannot be longer than 100 characters' } } } });
The Angular application I maintain on GitHub to demonstrate vadacl has been updated with a demo that uses generateForm().