Search code examples
angulartypescriptangular-formbuilder

Angular FormBuilder validator with new instance


i hope everyone is ok. I search a lot for this question but without sucess. Im tryng to put validator on formbuilder with a instance of a class. Exemple below:

This is my component.ts file where i clear my formbuilder when component init;

  reset() {
    this.item_ctrl = new ItemController();
    this.item.itemForm = this.fb.group(
      this.item_ctrl.get //get the item in the controller
      //where to put validator?
      //how to validate separate variables?
    )
  }

Here is my controller

export class ItemController {
    _item: Item;

    constructor() {
        this._item = new Item();
    }

    public get get(): Item {
        return this._item;
    }
    public set(item: Item) {
        this._item = item;
    }
}

Here is my class

export class Item {
    id: number;
    description: string;
    //here where are my variables...
}

Hope you can understand.(sorry for bad english)


Solution

  • im not sure, is that what you need but

    control - this.myForm.addControl('newFormName', new FormControl('', [Validators.required]));

    formGroup - const newGroupForm = this.fb.group({ id: [''], text: ['',Validators.required]}); this.myForm.addControl('yourGroupName',newGroupForm);