在更复杂的形式应该做什么?

时间:2018-03-01 17:33:06

标签: angular

我正在使用Angular5中的ReactiveForms并尝试找到一种好方法。

所以,在我的用例中,我在example.component.ts中有一个FormGroup,当我需要添加一些FormControl时,我必须这样做:

ngOnInit() {
  this.form = new FormGroup({
    'myCompany': new FormControl(this.company, Validators.required),
    'myId': new FormControl(),
    'myDate': new FormControl(new Date().toISOString(), Validators.required),
    'mySotck': new FormControl('', Validators.required),
    'myItemsStock': new FormControl([], Validators.required)
  });

//[...] more codes
好吧,到目前为止,一切都运作良好,没什么大不了的。但是我的example.component.ts有一些字段,其中一些字段有一些特殊的行为,如下所示:

ngOnInit() {

  // [...] more codes

  this.form.get('operation').valueChanges.subscribe(value => {

    if (!isNullOrUndefined(value)) {
       const operacao: MyModel = value;

      if (operacao.something) {
        this.limitDate = new Date();
      }

      if (!operacao.something) {

        this.service.search(this.company).subscribe(response => {
          const dateOffset = (24 * 60 * 60 * 1000) * response.days

          this.limitDate = new Date(new Date().getTime() - dateOffset);
        });
      }
    }

  });

  // [...] more codes

'因为我的组件获得了很多行代码,更多400行。我觉得阅读,理解和维护都很困难。

为了解决这个问题,我考虑创建一个新类,扩展FormGroup,然后在这个新类中设置我的FormControls,Validations和行为:

export class CustomFormGroup extends FormGroup {

  constructor() {
    super({
      'myCompany': new FormControl(this.company, Validators.required),
      'myId': new FormControl(),
      'myDate': new FormControl(new Date().toISOString(), Validators.required),
      'mySotck': new FormControl('', Validators.required),
      'myItemsStock': new FormControl([], Validators.required)
    });
  }

  registerListeners() {
    this.get('operation').valueChanges.subscribe(value => {

      if (!isNullOrUndefined(value)) {
        const operacao: MyModel = value;

        if (operacao.something) {
          this.limitDate = new Date();
        }

        if (!operacao.something) {

          this.service.search(this.company).subscribe(response => {
            const dateOffset = (24 * 60 * 60 * 1000) * response.days

            this.limitDate = new Date(new Date().getTime() - dateOffset);
          });
        }
      }
    }
  }

我的目的是降低组件的复杂性,使其更易于阅读和理解。 并将管理表单的责任分为另一个类,所以当我需要使用表单时,我可以这样使用它:

// example.component.ts
this.form = new CustomFormGroup();

使用这种方法,一旦我的自定义FormGroup包含,我就不需要在我的组件中有任何形式的行为。 我的问题是,这是否是分离问题的最佳方式,以及做得更好的方法。

如果您给我一些想法,分享您的经验或对此方法的反馈,我将非常高兴。完全可以自由评论这个问题。

对不起,如果我写的内容很难理解,英语不是我的主要语言,我每天都在努力改进。

0 个答案:

没有答案
相关问题