Last active
February 23, 2017 16:49
-
-
Save emolr/da01ea1c7e91972b790eac0c48dcca5e to your computer and use it in GitHub Desktop.
Article Model for angular 2, as part of a article written on medium
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // article-form.model.ts | |
| import {FormGroup, FormControl, Validators} from "@angular/forms"; | |
| import {IArticle} from "./article-form.interface"; | |
| export class ArticleModel { | |
| public id: string; | |
| public authorId: string; | |
| public title: string; | |
| public description: string; | |
| public content: string; | |
| public published: boolean; | |
| /*Here we build the model object | |
| that will hold all form values.*/ | |
| constructor(data: IArticle) { | |
| Object.keys(data).forEach(val => { | |
| this[val] = data[val]; | |
| }); | |
| } | |
| } | |
| export class ArticleFormModel { | |
| public form: FormGroup; | |
| public internalModelData: IArticle; | |
| /*Validators defines validators for field by name, | |
| further down these validators will be provided to the form*/ | |
| public validators = { | |
| id: Validators.required, | |
| userId: Validators.required, | |
| title: [Validators.required, Validators.minLength(1)], | |
| description: Validators.required, | |
| content: Validators.required | |
| }; | |
| constructor(data: IArticle) { | |
| this.internalModelData = new ArticleModel(data); | |
| this.form = new FormGroup({}); | |
| /*Here we loop over each data field passed through | |
| the constructor, and dynamically constructs the form*/ | |
| Object.keys(this.internalModelData).forEach(control => { | |
| this.form.addControl(control, new FormControl(this.internalModelData[control] || null)); | |
| }); | |
| /*Then we are providing the validators | |
| from the validator object from above.*/ | |
| Object.keys(this.validators).forEach(validator => { | |
| if (this.form.controls[validator]) { | |
| this.form.controls[validator].setValidators(this.validators[validator]); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment