It's here.

We have a first draft of working code for TanStack Form Angular Adapter!

Take a look at the implementation below and make sure to provide your feedback on how you feel with the current proposal.

Do it directly in comments on GitHub or under this post.

[WIP] Angular adapter by crutchcorn · Pull Request #627 · TanStack/form
Hi Enea This PR starts an initial Angular adapter that has an API like so: import { Component } from ‘@angular/core’ import { injectForm, TanStackField } from ‘@tanstack/angular-form’ import { NgF…

Code:

import { Component } from '@angular/core'
import { injectForm, TanStackField } from '@tanstack/angular-form'
import { NgFor } from '@angular/common'

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [TanStackField, NgFor],
  template: `
    <form (submit)="handleSubmit($event)">
      <ng-template
        [tanstackField]="form"
        name="firstName"
        [validators]="{ onChange: required }"
        let-field
      >
        <label>
          <div>First name:</div>
          <input
            [value]="field.state.value"
            (blur)="field.handleBlur()"
            (input)="field.handleChange($any($event).target.value)"
          />
        </label>
        <div *ngFor="let error of field.state.meta.errors" style="color: red">
          {{ error }}
        </div>
      </ng-template>
      <button>Submit</button>
    </form>
  `,
})
export class AppComponent {
  required = ({ value }: { value: string }) => {
    return !value ? 'Required' : undefined
  }
  form = injectForm({
    defaultValues: {
      firstName: 'Ryan',
      age: 25,
    },
    onSubmit({ value }: any) {
      console.log({ value })
    },
  })

  handleSubmit(event: SubmitEvent) {
    event.preventDefault()
    event.stopPropagation()
    void this.form.handleSubmit()
  }
}

Is this how you imagined an alternative for Template Driven/Reactive Forms?

Tagged in:

Bite-Sized

Last Update: March 17, 2024