Reputation: 3044
I'm practicing Angular-Forms using the template driven approach. I'm aiming to build a UI to contain the result of my data like this:
<hr>
<div class="well well-lg">
<p>Email Address: <span class="bg-info">{{data.email}}</span></p>
<p>Subscription Type: <span class="bg-info">{{data.sub}}</span></p>
<p>Password: <span class="bg-info">{{data.pass}}</span></p>
</div>
So my data
object in typescript will take these 3 props as strings I currently have this as the initializer: data: {email: string, sub: string, pass: string};
And in the constructor I have:
this.data.email = '';
this.data.sub = '';
this.data.pass = '';
And on form submit I have:
if(this.myForm.valid){
this.data.email = this.myForm.value.email;
this.data.sub = this.myForm.value.subscription;
this.data.pass = this.myForm.value.password;
this.myForm.reset();
}
On reload I'm getting: ERROR TypeError: Cannot set property 'email' of undefined
I'm 99% sure it's because of the way I'm declaring this object. But it seems like I declare it -> give types to it's properties -> give default values in the constructor. But in the constructor this.data is undefined.
What's the typescript way of doing this?
Upvotes: 1
Views: 432
Reputation: 923
Data is not defined so you can not append properties to the undefined object. Please try this in your constructor:
this.data = {
email: '',
sub: '',
pass: '',
};
Upvotes: 1