將 angular2 升至 RC2 後,就出現了一段警告訊息:
*It looks like you're using the old forms module. This will be opt-in in the next RC, and
will eventually be removed in favor of the new forms module. For more information, see:
https://docs.google.com/document/u/1/d/1RIezQqE4aEhBRmArIAS1mRIZtWFf6JxN_7B4meyWK0Y/pub
看來在 RC2 後,ngForm 做了一番修正,需要做一些破壞性的處理,
以下是將舊版 ngForm 升級至新版的步驟:
(目前已升至 RC3 )
1. main.ts 加入:
import { disableDeprecatedForms, provideForms }
from '@angular/forms';
bootstrap(AppComponent, [disableDeprecatedForms(), provideForms() ]);
2. component 修改部分:
import {CORE_DIRECTIVES, FORM_DIRECTIVES, NgForm, Control}
from '@angular/common';
...
@Component({
directives: [FORM_DIRECTIVES]
})
修正為:
import {CORE_DIRECTIVES} from '@angular/common';
import {REACTIVE_FORM_DIRECTIVES, FormControl, FormGroup}
from '@angular/forms';
...
@Component({
directives: [REACTIVE_FORM_DIRECTIVES]
})
3. form class 更名,尤其是有用 FormBuilder 做客製化驗證的部分:
REACTIVE_FORM_DIRECTIVES:
- formGroup (deprecated: ngFormModel)
- formControl (deprecated: ngFormControl)
- formControlName (deprecated: ngControl)
- formGroupName (deprecated: ngControlGroup)
- formArrayName (deprecated: ngControlGroup)
- FormControl() (deprecated: Control)
- FormGroup() (deprecated: ControlGroup)
- FormArray() (deprecated: ControlArray)
- FormBuilder (same)
- Validators (same)
4. form control ( input, select...),需加上 name attribute,
#name="ngForm" 要改為 #name="ngModel":
<input type="text" class="form-control" required
[(ngModel)]="name"
ngControl="name"
#name="ngForm" />
修改為:
<input type="text" class="form-control" required
[(ngModel)]="name"
ngControl="name"
name="name"
#name="ngModel" />
5. ngFormModel, ngControl 修改部分 ( HTML ):
<form #templateForm="ngForm"
[ngFormModel]="_form" />
<input type="text" class="form-control" required
[(ngModel)]="TemplateName"
pattern="^[a-zA-Z0-9_.\-\u4e00-\u9fa5-\(-\)\s]+$"
ngControl="TemplateName" />
</form>
修改為:
<form #templateForm="ngForm"
[formGroup]="_form" />
<input type="text" class="form-control" required
name="TemplateName"
[(ngModel)]="TemplateName"
pattern="^[a-zA-Z0-9_.\-\u4e00-\u9fa5-\(-\)\s]+$"
formControlName="TemplateName" />
</form>
6. ngFormModel, ngControl 修改部分 ( typescript)::
_form: ControlGroup;
constructor(
@Inject(FormBuilder) fb: FormBuilder
) {
this._addTemplateForm = fb.group({
TemplateName: ['', Validators.required]
})
}
修改為:
_form: FormGroup;
constructor(
@Inject(FormBuilder) fb: FormBuilder
) {
this._addTemplateForm = fb.group({
TemplateName: ['', Validators.required]
})
}
升級步驟大致如上,希望可以幫助到各位囉!