0

I have a form with currently one field description and I'm building that form from a model as given below

view-model.ts

export class ViewModel {
  description = '';
}

view-action.component.ts

export class ViewActionComponent {
  constructor(public fb: FormBuilder) {
    this.groupForm = this.fb.group(new ViewModel());
  }
...
}

The form works perfectly fine. Now the problem is I need to add validator for that description field (like entering only text). Is there any way to add a validator for description in view-model.ts file so that I wont modify view-action.component.ts file?

So the basic idea is, If I need to add another field with validator, I can do it in the ViewModel itself.

1 Answer 1

2

So your problem is that you want to build your form using your view-model.ts class.

The problem with building a form by passing in an object:

this.fb.group(new ViewModel())

Is that form builder only uses the state in that object to create the form values. It's not a set of instructions on how to build a more complex form with validation. You need to build complex forms by interacting with the form builder for each control.

To achieve this you could let your view model build the form:

export class ViewModel {
  description = '';

  private form: FormGroup;

  createForm(formBuilder: FormBuilder): FormGroup {
    this.form = formBuilder.group({
      description: formBuilder.control(this.description, {
        validators: [
          Validators.required
        ]
      })
    });
    return this.form;
  }

  update() {
    this.description = this.form.get('description').value;
  }
}

So now your component simply gets the form like this:

this.groupForm = this.viewModel.createForm(this.fb);

And on submit, your component instructs your view model that it can update itself from the form.

onSubmit() {
  this.viewModel.update();
}

DEMO: https://stackblitz.com/edit/angular-tm8abx

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the reply. But you missed my point. My model and formgroup are in different files.In your example, its on the same file. right
Oh, I think I see what you're trying to achieve. So you want Angular to magically created a required validator from some set of values?
I think trying to create a complex form from this.fb.group(new ViewModel()) is asking a lot. If you want to keep modifications in view-action.component.ts to a minimum, you could have some createForm function on your view model - I've modified the view model in my demo.
Sorry, I've not updated my demo, I forked it stackblitz.com/edit/angular-tm8abx
No prob :) I'll edit my answer with your problem and solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.