Working on honing my skills with Angular Forms utilizing the template-driven approach. My goal is to construct a user interface to display the output of my data in this structure:
<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>
In my typescript file, I have defined my data
object with three properties initialized as strings:
data: {email: string, sub: string, pass: string};
Within the constructor, I have set the initial values of these properties to empty strings:
this.data.email = '';
this.data.sub = '';
this.data.pass = '';
Upon form submission, I have implemented the following logic:
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();
}
However, upon reloading the page, I am encountering this error:
ERROR TypeError: Cannot set property 'email' of undefined
I believe this issue is stemming from the way I am declaring the object. I have specified the types of its properties and provided default values in the constructor. Nonetheless, this.data
appears to be undefined within the constructor.
What is the proper way to handle this in TypeScript?