Skip to content

Make built-in validator directives standalone #56226

@chronospatian

Description

@chronospatian

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

@angular/forms

Description

I am building a set of configurable form field components that uses the directive composition API. I want to reuse Angular's built-in validator directives to define what validators are applicable to each field without re-implementing them in each form field component.

@Component({
  standalone: true,
  selector: 'form-field[type="project-id"]',
  imports: [MatFormFieldModule, MatInputModule, ReactiveFormsModule],
  template: `
    <mat-form-field>
      <mat-label>Project ID</mat-label>
      <input matInput [formControl]="control" />
      @if (control.hasError('required')) {
      <mat-error>Project ID is required</mat-error>
      }
    </mat-form-field>
  `,
  hostDirectives: [{
    directive: RequiredValidator, // TS-992014: Host directive RequiredValidator must be standalone
    inputs: ['required']
  }, {
    directive: FormFieldDirective // implements ControlValueAccessor
  }],
  providers: provideFormField(ProjectIdFieldComponent),
})
export class ProjectIdFieldComponent {
  control = new FormControl();
}
<form-field type="project-id" [(ngModel)]="projectId" [required]="required" />

Related issue: #51248

Proposed solution

Add the standalone flag to existing validator directives.

Alternatives considered

I am currently converting these to standalone directives myself.

@Directive({
  standalone: true,
  providers: [provideValidator(StandaloneRequiredValidator)]
})
export class StandaloneRequiredValidator extends RequiredValidator {}

...etc
@Component({
  hostDirectives: [{
    directive: StandaloneRequiredValidator, // now it works
    inputs: ['required']
  }],
})
export class ProjectIdFieldComponent {}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions