简体   繁体   English

Angular - 在对象的新属性中创建属性

[英]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 : 目前,我的html中有一个select元素,它有一个对象details的ngModel:

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

However, publicInformation may not exist in that object, or if it does, maybe firstname does not exist. 但是, publicInformation可能不存在于该对象中,或者如果它存在,则firstname可能不存在。 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. 基本上,如果select被触发,即使publicInformationfirstname都不存在,我想在details创建它们并存储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? 有人可以解释我在这里做错了什么,我怎样才能达到我想要的结果?

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. 但是,最好将此逻辑放在服务中,以便它们负责将所有必需的空属性添加到它们加载的数据中,或者如果您使用的是Redux,那么它应该进入reducers。

您需要将detailspublicInformation初始化为空对象

public details = {publicInformation : {}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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