I have created a model class with name registration.ts
export class CustomerRegistration{
customer: {
firstname : string;
lastname : string;
email: string;
}
password: string;
}
Then I have created a component and, in that component, I am trying to set value in above class
import { Component, OnInit } from '@angular/core';
import { CustomerRegistration} from 'src/app/classes/customer/registration';
@Component({
selector: 'app-userregistration',
templateUrl: './userregistration.component.html',
styleUrls: ['./userregistration.component.css']
})
export class UserregistrationComponent implements OnInit {
ngOnInit(): void {
}
register = new CustomerRegistration();
hello(){
this.register.customer.firstname= 'Karan';
console.log(this.register);
}
}
But when I am trying to set value in firstname I am getting below error
core.js:6456 ERROR TypeError: Cannot set properties of undefined (setting 'firstname')
Can anyone help me to set value of first name.
CodePudding user response:
Your customer
property is basically an array, so you cant access the inside properties with dot (.) operator.
You have to access it with array index, like this:
this.register.customer[0].firstname= 'Karan';
Here 0 is an index that will change dynamically based index value.
CodePudding user response:
Your customer
property should be instanciated. You can do it in your class constructor:
export class CustomerRegistration {
constructor(){
this.customer = {} as any;
}
customer: {
firstname: string;
lastname: string;
email: string;
};
password: string;
}
Also, consider using an interfaces like:
export interface ICustomer{
firstname : string;
lastname : string;
email: string;
}
export interface ICustomerRegistration{
customer: ICustomer;
password: string;
}
Then in your component:
Register:ICustomerRegistration = {customer:{} as ICustomer} as ICustomerRegistration;
Register.customer.firstname = 'Karan';