Search code examples
angularform-controlformgroups

How to make form Model in separate function(declaration,FormGroup and FromControl)


How to make form Model in separate function(declaration,FormGroup and FromControl) and call it in ngOnInit. Please help i am learning angular currently this are the basics I am working on.

export class AppComponent implements OnInit {
  myForm: FormGroup;

  ngOnInit() {
    this.myForm = new FormGroup({
      name: new FormControl('Sammy'),
      email: new FormControl(''),
      message: new FormControl('')
    });
  }

Wanted the this.myForm part in separate function and the how to call it.


Solution

  • You can create a function

    messageForm(data:any=null)
    {
        data={name:'',email:'',message:'',...data}
        return new FormGroup({
          name: new FormControl(data.name),
          email: new FormControl(data.email),
          message: new FormControl(data.message)
        });
    }
    
    //and use
    myForm:FormGroup=this.messageForm({name:'sammy'})
    

    If you want, this function can be "outside" the Component, simply create as function and mark as export to allow import using import {messageForm} from '...'

    export function messageForm(data:any=null){
       ...
    }
    

    And use

    myForm:FormGroup=messageForm({name:'sammy'})
    

    You can also create a Class

    export class MessageForm {
      form:FormGroup
      constructor(data: any = null) {
        data = { name: '', email: '', message: '', ...data };
        this.form= new FormGroup({
          name: new FormControl(data.name),
          email: new FormControl(data.email),
          message: new FormControl(data.message),
        });
      }
      get value(){
        return this.form.value
      }
      get controls()
      {
        return this.form.controls
      }
      get(path:string)
      {
        return this.form.get(path) as FormControl
      }
      setValue(path:string,value:any)
      {
        this.form.get(path).setValue(value)
      }
    }
    

    And you can use

    myForm = new MessageForm({ name: 'Sammy' });
    
    <form [formGroup]="myForm.form">
      <input formControlName="name"/>
      <input formControlName="email"/>
      <input formControlName="message"/>
    </form>
    

    stackblitz