简体   繁体   中英

Initialize an empty typescript object, but define it's properties

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?

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: '',
};

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM