3
votes

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

3

3 Answers

6
votes

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 = '';
}
2
votes

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);
    }

}
1
votes

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