Form Validator always triggered when defined in AbstractControlOptions

Discussão em 'Angular' iniciado por perissf, Fevereiro 8, 2025.

  1. perissf

    perissf Guest

    In a Reactive Form, I would like to use a validator that's not linked to a particular Form Control, but more at FormGroup level.

    Hence, I defined the validator using FormBuilder.group's AbstractControlOptions.

    In theory, to my understanding, the following Component shouldn't be validated at all, because the button is of type "Button", hence the form is never submitted. However the validator is triggered.

    Component

    @Component({
    selector: 'app-shop2',
    imports: [
    ReactiveFormsModule,
    CommonModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    ],
    template: `
    <form [formGroup]="formGroup" >
    <mat-form-field>
    <mat-label>Choice</mat-label>
    <input matInput placeholder="Choice" formControlName="choice">
    </mat-form-field>
    <button mat-button type="button" (click)="onClick()">Click Me</button>
    </form>
    `
    })
    export class Shop2Component {
    private _formBuilder = inject(FormBuilder);
    formGroup = this._formBuilder.group({
    choice: this._formBuilder.control(''),
    }, { validators: customValidator(), updateOn: 'submit' });

    onClick(): void {
    console.log(this.formGroup.get('choice')?.value);
    }
    }

    Continue reading...

Compartilhe esta Página