1

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?

1 Answer 1

1

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: '',
};
Sign up to request clarification or add additional context in comments.

1 Comment

I see.... I got around this by just jamming it all outside the constructor: data: {email: string, sub: string, pass: string} = { email: '', sub:'', pass:'' }; But I feel like that's a bad idea. Thanks for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.