Going over the Angular2 docs on forms, and decided to bring forward my 1.x simple forms demo
It ports over fairly well, but a significant number of changes needed to be made. Honestly it seems like it would take an enormous effort to convert an existing 1.x application to Angular2.
Specific Changes
- update directives
ng-model->[(ngModel)]ng-class->[ngClass]ng-submit->(ngSubmit)ng-show->[hidden](could have also used*ngIf)ng-maxlength->[maxlength]ng-disabled->[disabled]
- instead of defining a telephone
filter, I created apipe - Create
ManufacturerServicewith atypeclass and amock - Create generic
LookupServicefor the list of states angular.copy()does not have a direct replacement in Angular2.Object.assign()works well as long as a deep copy is not needed, which isn’t the case here (Manufacturer doesn’t contain collections, just simple types)- instead of defining an empty manufacturer JSON object, we can instantiate a new, empty manufacturer. (to be used when the
newbutton is clicked) - The
currencyfilter will not work with an empty string. In edit mode, blanking out the<input>causes<span class="displayValue" [ngClass]="pageMode">{{manufacturer.creditLimit | currency }}</span>to raise an exception. The workaround is to set the<input type="number"- alternately, one could argue that the view controls should not be bound to the same object the edit controls are bound to
- I wasn’t able to access the
manufacturerFormproperly from thesimple-edit-form.component.ts.- within the template,
manufacturerForm.validis available, but in thecomponent.tsit is undefined - ended up using
manufacturerForm.checkValidity() - this plunker (not mine) shows the forms
validproperty as accessible incomponent.ts, but I didn’t get this to work
- within the template,
- needed to set
#manufacturerForm="ngForm"inside the<form> - In addition to the
id,nameattributes, needed to set#nameInput="ngModel"inside the<input>’s using validation. - spent a lot of time figuring out why
nameInput.errors.requiredwas giving undefined errors. It looks like you always need to check forvalidfirst, as theerrorscollection is only defined when errors are present:[hidden]="nameInput.valid || !nameInput.errors.required"The||causes a short-circuit evaluation in the expression. If you remove thenameInput.validfrom the example below you can repro this issue.