3

Is there a way to create a reactive form basing on an existing data model with all the validation magic. In the example below author passes whole new object into a formbuilder but what I want to achieve is elegant way to tell formbuilder what field is required or needs some other validation.

https://malcoded.com/posts/angular-fundamentals-reactive-forms

export class PersonalData {
  email: string = '';
  mobile: string = '';
  country: string = '';
}
...
createFormGroupWithBuilderAndModel(formBuilder: FormBuilder) {
    return formBuilder.group({
      personalData: formBuilder.group(new PersonalData()),
      requestType: '',
      text: ''
    });
  }

I just want to skip the process of assigning a FormControl for each field in the model.

@EDIT

After some research and little hint from @xrobert35 I wanted to try and used https://www.npmjs.com/package/@rxweb/reactive-form-validators

1
  • I wish the form was just bindings directly to my model, and the constraints were just made as html-attributes. I have a rather complicated model, and it requires so much boiler-plate to go model-to-form and back form-to-model. For editing an existing model, I'm storing references back to the original entity. Not sure if there's a cleaner way. :/ Commented Aug 17, 2022 at 17:43

3 Answers 3

6

They could be "many" way to do what you want to do, but by just extending your actual solution : Your personnal data could look like :

export class PersonalData {
  email: string = ['', Validators.required];
  mobile: string = ['', Validators.required, Validators.maxLength(10)];
  country: string = '';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, I thought about that but is it really elegant to mix up 'Validators' with data model classes?
Like I writed it, it's absolutly not elegant, And it would not put this class in my "model" but it can be a "detached" elegant way to declare a Form. I didn't had time to search but I supposed that someone could already have made a "Decorator based model". With '@Email' '@Required' '@MaxLenght' etc :) that would be an elegant way
2

If you need domain base validation (for reusable purpose) you can use rxweb validations.

export class PersonalData {
    @required()
    email: string;

    @required()
    mobile: string;    

    @greaterThan({ fieldName: 'number2' })
    number1: number;
    
    @prop()
    number2: number;
}

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    formGroup: FormGroup;
    constructor( private validation: RxFormBuilder) {
    }

    ngOnInit() {      
        let person: PersonalData = new PersonalData();
        this.formGroup = this.validation.formGroup(person);
    }

}

Comments

1

If I understand you just want to add validators to your field.

https://angular.io/guide/form-validation

I can't be more precise to giving you the official documentation.

ngOnInit(): void {
  this.heroForm = new FormGroup({
    'name': new FormControl(this.hero.name, [
      Validators.required,
      Validators.minLength(4),
      forbiddenNameValidator(/bob/i) // <-- Here's how you pass in the custom validator.
    ]),
    'alterEgo': new FormControl(this.hero.alterEgo),
    'power': new FormControl(this.hero.power, Validators.required)
  });

}

In this exemple the fields name and power are required and of course the syntaxe could differ but the flow is the same.

Does it helps you ?

@EDIT There is the same post for your use case: https://stackoverflow.com/a/47576916/7133262

2 Comments

No, I did not want to specify each FormControl but rather get them from passed class object.
Yes and correct me if Im wrong but I think this solution instigates me to put FormControls inside the model itself. I want to avoid that.

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.