interview community logo

1
0
Difference between Template driven and Reactive forms
1 answer

What's the difference between Template driven and Reactive forms?

Angular Robert Isaac asked 9 months ago


0

template driven forms is from its name are mainly in the template (HTML) while reactive is mainly in the TS file

template driven example

@Component({
  selector: 'app-template-form',
  standalone: true,
  imports: [CommonModule, FormsModule],
  template: `
    <form #form="ngForm">
        <input name="username" [ngModel]="loginForm.username" required>
        <input name="password" [ngModel]="loginForm.password" required>
        
        <button [disabled]="form.invalid">Submit</button>
    </form>
  `,
})
export class TemplateFormComponent {
  loginForm = {username: '', password: ''};
}

here is reactive form example

@Component({
  selector: 'app-reactive-form',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule],
  template: `
      <form [formGroup]="loginForm">
          <input formControlName="username">
          <input formControlName="password">

          <button [disabled]="loginForm.invalid">Submit</button>
      </form>`,
})
export class ReactiveFormComponent {
  private readonly formBuilder= inject(FormBuilder).nonNullable;
  loginForm = this.formBuilder.group({
    username: ['', [Validators.required]],
    password: ['', [Validators.required]],
  });
}

adding validation is easier in the reactive forms, building complex forms is also more robust with reactive forms because they are strongly typed so if you mistyped something or trying to access something in a wrong way it will give you an error

as a rule of thumb, if you have a very simple form use template driven, but if you have complex form or if you need custom validation that not available in native HTML then use reactive forms, if you are not sure I suggest to go for reactive

Robert Isaac answered 9 months ago loading comments...