javascripthtmlangularangular-reactive-formslifecycle

ngOnInit in an Angular reactive form


I am building a form with Angular reactive forms and i want to set a form control value with a property from a service, but when i submit the form, the form control value is not what I expected (the property value from the service) but the value from the component.

mycomponent.ts:

  ngOnInit(): void {
        this.date = this.calendarService.date;
    }

  public date:string = "test";

  public payForm: FormGroup = this.formbuilder.group({
    date: [this.date, [], []],
  })

mycomponent.html

<form id="payform" [formGroup]="payForm" >
  <input matInput [value]="date">
</form>

I am confused about how the component lifecycle works here, because the form is created i can see the value from the service in the screen.

Can you help me to understand how to send the value correctly? thank you


Solution

  • you need to declare the date and the form outside the onInit and then initialize the for in the OnInite method

     export class MyComponent implements OnInit {
      public date: string = "test";
      public payForm: FormGroup;
    
      constructor(private formbuilder: FormBuilder, private calendarService: CalendarService) {}
    
      ngOnInit(): void {
        this.date = this.calendarService.date;
    
        this.payForm = this.formbuilder.group({
          date: [this.date, [], []]
        });
      }
    }
    

    make a onSubmit method to get the form value

    <form id="payform" [formGroup]="payForm" (ngSubmit)="onSubmit()">
      <input matInput formControlName="date">
      <button type="submit">Submit</button>
    </form>