EDJ
EDJ

Reputation: 1023

Angular - Create property in new property of object

Currently, I have a select element in my html which has a ngModel to the object details:

[ngModel]="details?.publicInformation?.firstname" 

However, publicInformation may not exist in that object, or if it does, maybe firstname does not exist. No matter the case, in the end, I want to create the following:

[ngModel]="details?.publicInformation?.firstname" (ngModelChange)="details['publicInformation']['firstname'] = $event"

Basically, if the select is triggered, even if neither of publicInformation nor firstname exist, I would like to create them inside details and store the value from the select.

The issue is that I am getting

Cannot set property 'firstname' of undefined

Can someone explain what I am doing wrong here and how can I achieve the result I desire?

Upvotes: 3

Views: 2387

Answers (2)

Muhammed Albarmavi
Muhammed Albarmavi

Reputation: 24424

You need to initialize details and publicInformation to empty object

public details = {publicInformation : {}};

Upvotes: 1

Danziger
Danziger

Reputation: 21161

You should do that when you load the form data.

For example, you might have something like this:

ngOnInit() {
    this._someService.loadForm().then((formData: FormData) => {
        this.details = formData;
    });
}

Then, you could modify that to fill in the missing empty properties you need:

ngOnInit() {
    this._someService.loadForm().then((formData: FormData) => {
        this.details = formData || {};

        if (!this.details.publicInformation) {
            this.details.publicInformation = { firstname: '' };
        } else if (!this.details.publicInformation.firstname) {
            this.details.publicInformation.firstname = '';
        }
    });
}

However, it would be better to place this logic in the services, so that they are responsible for adding all the necessary empty properties to the data they load, or if you are using Redux, then it should go into the reducers.

Upvotes: 1

Related Questions