abnormi
abnormi

Reputation: 688

Angular mat-form-field encapsulated in child component

is there an easy to follow example which shows how to encapsulate a mat-form-field in a child component?

What I want

<form [formGroup]="form">
  <my-component 
      formControlName="someFormValue"
      label="hi">
  </my-component>
<form>

and in my-component.html

<mat-form-field>
  <mat-label>
    {{ label }}
  </mat-label>
  <input
    matInput
    ...
  />
  <mat-error>
    .... some form validation errors here
  </mat-error>
</mat-form-field>

Cheers...

Upvotes: 1

Views: 1495

Answers (1)

Eliseo
Eliseo

Reputation: 57941

the best bet is pass as @Input the FormControl -not the formControlName-

  <my-component 
      [control]="form.get('someFormField')"
      label="hi">
  </my-component>

and use in the component

@Input()control:FormControl

//in .html

<mat-form-field>
  ...
  <!--see that you use [formControl] directly-->
  <input matInput [formControl]="control"/>
  <mat-error>
    .... some form validation errors here...
  </mat-error>
</mat-form-field>

Updated: a quick stackblitz

Upvotes: 1

Related Questions