如何在角度应用程序中维护为一组属性/表单域键?

时间:2018-11-11 19:22:21

标签: angular enums angular-reactive-forms

因此,我正在使用Angular应用程序,其中用户将跨多个视图创建配置文件。用户每次会话仅创建一个配置文件,并将通过反应性表单字段输入数据。

我正在考虑一种可跟踪概要文件当前状态的可注射服务。然后,在每个视图中都有一个formGroup,并且在每个onSubmit上,配置文件信息都从formGroup传输到服务维护的唯一会话实例。

对于每个视图,我将不得不在模型中,Profile类以及不同表单组中重复配置文件字段的名称。因此,在模型Profile类中必须有一个name,在要输入名称的View的FormGroup中必须有一个export enum ProfileFieldsEnum { NAME = 'name', EMAIL = 'email' } 。我不想每次想写入一个字段或为其创建FormControl时都输入一个硬编码的字符串。我考虑过在外部文件中创建一个枚举,然后将其导入模型类和不同视图的组件中。所以:

import { ProfileFieldsEnum } from './profile-fields-keys';

export class Profile {

    private profileFieldsKeys = Object.keys(ProfileFieldsEnum).filter(k => typeof ProfileFieldsEnum[k as any] === 'number');
    private profileFieldsValues = new Set(this.profileFieldsKeys.map(k => ProfileFieldsEnum[k as any]));

    constructor() {}

    setProperty(key: string, value: any) {
        if (this.profileFieldsValues.has(key)) {
            this[key] = value;
        }
    }

    getProperty(key: string): any {
        return this.profileFieldsValues[key];
    }
}

然后将被用作:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { LoggerService } from 'src/app/services/logger.service';
import { Profile } from 'src/app/model/profile';
import { ProfileFieldsEnum } from 'src/app/model/profile-fields-keys';    

@Component({
  selector: 'profile-search',
  templateUrl: './profile-name.component.html',
  styleUrls: ['./profile-name.component.scss']
})
export class ProfileNameComponent implements OnInit {

  constructor(
    private fb: FormBuilder,
    private logger: LoggerService
  ) {}

  ngOnInit() {
    this.profileParentForm = this.fb.group({
      name: ['', Validators.required]    // Here I'd like to use ProfileFieldsEnum.NAME instead of 'name'
    });

    this.profileParentForm.valueChanges.subscribe(form => 
    this.logger.log(form));
  }
}

在模型类中,如下所示:

onSubmit

我仍然没有编写{{1}}代码。

所以我想我不是第一个遇到这种情况的人。你们做了什么?你会怎么做?随时对我的任何想法发表评论,我觉得我对细节有些困惑,错过了一些总体情况。必须有一个更简单的方法来实现此目的。

1 个答案:

答案 0 :(得分:1)

是的,您的代码可以简化为-

个人资料

让我们重构您的个人资料类。到目前为止,它已经进行了添加过程来分别保存键和值的记录,但是可以将其更改为-

import { ProfileFieldsEnum } from './profile-fields-keys';

export class Profile {

    private profile = {}; // it will add the property and value dynamically

    constructor() {}

    setProperty(key: string, value: any) {
       this.profile[key] = value; //set the property value, create new one if doesn't exist
    }

    getProperty(key: string): any {
        return this.profile[key];
    }
}

ProfileNameComponent

如果不想对属性名称进行硬编码,那么可以使用枚举来实现。

  ngOnInit() {
    this.profileParentForm = this.fb.group({
       [ProfileFieldsEnum.NAME]: ['', Validators.required] //<-- enum is used for control name
    });

    this.profileParentForm.valueChanges.subscribe(form => 
    this.logger.log(form));
  }