I'm working on a project using angular 2. I'm dealing with forms and validation and I have an issue. I've just found a workaround but I would like to know why my original code doesn't works.
Here is my code (refractored) :
@Component({
directives: [ DisplayErrorComponent ],
styleUrls: ["src/modules/component@channel/src/add/add.css"],
template: `
<form (ngSubmit)="onSubmit()" [ngFormModel]="channelForm">
<label for="link">
Customize the link
<!--<div class="link inputBordered inputTexted" [ngClass]="{error: !channelForm.controls.link.valid}">-->
<div class="link inputBordered inputTexted" [class.error]="!channelForm.controls.link.valid">
<span class="static">http://www.monsite.fr/mediatheque/</span>
<input type="text" name="link" ngControl="link" required>
</div>
</label>
<input type="submit" value="Add" [disabled]="!channelForm.valid">
</form>
`
})
export class EditComponent {
channel: Media;
channelForm: ControlGroup;
categories: Category[] = this._categoryService.listAll();
constructor(fb: FormBuilder, private _categoryService: CategoryService, private _routeParams: RouteParams, private _mediaService: MediaService) {
this.channel = this._mediaService.getById(this._routeParams.get('id'));
this.channelForm = fb.group({
link : fb.control(this.channel.link, Validators.compose([Validators.required, UrlValidator])),
});
}
onSubmit():void {
console.log('form submitted')
}
}
The anomaly is at line 8-9. You can see a commented line. When I use [class.error]="true"
, Angular throws an error :
EXCEPTION: Error: Uncaught (in promise): No provider for ControlContainer! (NgControlName -> ControlContainer)
But when I try with [ngClass]
, everything works. Why ? (I can post all the edit.component.ts
code if needed).
You need to use this instead:
<input type="text" name="link"
[ngFormControl]="channelForm.controls.link" required>
Because ngControl
is for inline form declaration and you use FormBuilder to define your link
control.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.