Skip to content

Signal forms: applyEach: add index to SchemaFn arguments #67241

@wimbarelds

Description

@wimbarelds

Which @angular/* package(s) are relevant/related to the feature request?

forms

Description

In signal forms you can validate items in an array using, for example:

const uniqueItems = schema<string[]>(items => {
  applyEach(items, item => {
    validate(item, ({value, valueOf, index}) => {
      const firstValueIndex = valueOf(items).indexOf(value());
      return index() === firstValueIndex ? null : { kind: 'duplicate', message: 'Items must be unique' };
    });
  });
});

This is already a little bit messy, but quite workable.

However if you're not validating item, but item.property, you lose access to ctx.index.
For example:

const uniqueItems = schema<Array<{ property: string, propertyValue: string }>>(items => {
  applyEach(items, item => {
    validate(item.property, ({valueOf}) => {
      // ctx.index is not available when validating item.property
    });
  });
});

You could still access the index via valueOf(items).indexOf(valueOf(item)), but this does become messy somewhat quickly.

You could also validate form.items as a whole, but if you want the error message to be applied to a specific item in the array- I dont think that's possible?

Proposed solution

applyEach could provide a second argument to its schemaFn, namely index.

Alternatively, perhaps indexOf could be added to FieldContext so ctx.indexOf(item) could be used.

Alternatives considered

As said, it is possible to valueOf(items).indexOf(valueOf(item)), that solution does feel quite a bit less elegant and has a bit of a code-smell to me.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    Status

    Done

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions