I have a form created using Form Builder (Angular2 Beta 1, TypoScript), i.e.: there’s something like this in constructor
:
this.form = this._formBuilder.group({
'username': ['', Validators.required],
'email': ['', Validators.required]
});
The form shows up, everything is nice so far. What I don’t really get is how I handle the binding when I load the data (in this case: a User object) from a remote service (or some other asynchronous loading mechanism).
What I have tried, is:
constructor
or ngOnInit
. Problem: Throws an exception, even before the loading starts (“Cannot read property 'validator' of undefined …”)constructor
or ngOnInit
, but before that create an empty form. Problem: validation does not work.User
object, and set properties of that object. Problem: no exception, but the data does not show up in the form.I guess there must be some smarter/better way to get this working? I’m rather new to Angular2, so I hope the question is not too dumb …
---- Update ----
First, I forgot to mention that I use ngFormModel
in the form – in case it’s important.
And @Thierry: I think that “temporary empty object to bind with the form” is what I tried to do (the 3rd approach mentioned above) but what didn’t work. Precisely, I tried this:
constructor(private _formBuilder:FormBuilder) {
this.user = new User;
this.user.username = 'abc';
this.form = this._formBuilder.group({
'username': [this.user.username, Validators.required],
});
}
This displays the username, but it doesn’t even work when I move the line which sets this.user.username
to the end of the constructor – which I find pretty surprising, as I would have expected data binding to take care of this.
You can separate your username and email in Control object, than append it to form. You will have more control with that ( you can update it later ).
form: ControlGroup;
email: Control = new Control("");
name: Control = new Control("");
constructor(public fb: FormBuilder) {
this.form = fb.group({
email: this.email,
name: this.name
});
setTimeout(() => {
this.email.updateValue("invalid email");
this.name.updateValue("Name");
}, 3000);
}