Home > Software engineering >  Binding formControl to external formGroup in Angular makes mat-error not to work
Binding formControl to external formGroup in Angular makes mat-error not to work

Time:11-26

I need to bind a formControl to a form with a formGroup without being nested into it, and keeping the default mat-errot error state matching.

I have tried

app.component.html

<form [formGroup]="formAdd" (ngSubmit)="onSubmit()"></form>



<!-- somewhere else in the same file -->



<mat-form-field>
<input matInput [formControl]="formAdd.controls.username">
<mat-error>Username is required</mat-error>
</mat-form-field>

app.component.ts

ngOnInit(): void {
    this.formAdd = this._formBuilder.group({
      username: ['', [Validators.required]]
    });
}

However when I do it like that, the mat-error doesn't appear when the form is submitted and the input is empty. I can't put the input inside the form as it goes inside a custom component with other inputs not related to the form.

Inspecting further, the errorStateMatcher says that the form of the control is null and so it cannot check if it is submitted or not, and so it never shows the mat-error.

Is there a way to bind an input to an external form and keeping the validation logic?

CodePudding user response:

Use are using this wrong way. Firstly take your matformfield inside form.

    <form [formGroup]="formAdd"(ngSubmit)="onSubmit()">
<mat-form-field>
<input matInput formControlName="username">
<mat-error>Username is required</mat-error>
</mat-form-field>
</form>

CodePudding user response:

It would help if you could elaborate a little bit more on what you are trying to achieve here so we can focus on that and provide solutions. There are different paths that lead to Rome, but a good programmer chooses or finds the most efficient way of getting there. Inputs are just places for data collection, you can have different inputs (formcontrols) in different parts of your view template and all you have to do is grab their value upon some kind of event.

So in your .ts file:

// Declare a formControl variable   
username = new FormControl('', Validators.required);

onSubmit(){
    const userName = this.username.value;
    // Grab the value and from here you can go anywhere
 }
  • Related