0

In MVC or Rest APIs we have model classes (DTOs) to transfer data. How can we create those model classes and use them for reactive forms in Angular?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Salman Khan
  • 53
  • 2
  • 9
  • try this https://stackoverflow.com/questions/49997765/reactive-forms-correctly-convert-form-value-to-model-object – Eric Li Jul 29 '19 at 17:02

1 Answers1

1

I have used the package(@rxweb/reactive-form-validators) in my project for model based reactive form validation.

For your understanding I have copied the code from the stackbliz example of repective article "New way to validate the reactive forms"

You can define the validation on top of the property through validation decorators. See the below code User class and applied @required validation decorator.

import { required,compare } from "@rxweb/reactive-form-validators";

export class User {

    @required()
    userName: string;

    @required()
    password: string;

    @compare({fieldName:'password'})
    confirmPassword:string;

}

Here is the Component code, For creating a formgroup you have to use RxFormBuilder.

export class UserAddComponent implements OnInit {

    userFormGroup: FormGroup
    user:User;
    constructor(
        private formBuilder: RxFormBuilder
    ) { }

    ngOnInit() {
        this.user = new User();
        this.userFormGroup = this.formBuilder.formGroup(this.user);
    }
}

Finish. Bind the html as per you custom need.

StackBlitz Example

Ami Vyas
  • 119
  • 2
  • 9