Search code examples
angulartypescriptangular-materialangular-directiveangular-template

How to apply a given directive value to multiple tags in Angular Material?


I have recently started learning Angular and Material and in my project I realized, that I have to create forms with the same appearance. For instance the registration form's template looks like this:

<mat-card>
  <h2>{{'NAV.REGISTRATION' | translate}}</h2>
  <form [formGroup]="registrationForm" (ngSubmit)="submitRegistrationForm()">
    <div>
      <mat-form-field appearance="outline">
        <input matInput formControlName="fullName" placeholder="{{'REGISTRATION.NAME' | translate}} *">
      </mat-form-field>
      <mat-form-field appearance="outline">
        <input matInput formControlName="password" placeholder="{{'REGISTRATION.PASSWORD' | translate}} *" type="password">
      </mat-form-field>
...

I would like to apply appearance="outline" to all the <mat-form-field> tags in the template. I have tried applying <div class="mat-form-field-appearance-outline">, but of course it causes the <div> element to appear with the styles, not its children. Also, I can not just simply write

mat-form-field{
  appearance: outline;
}

in the template's .scss file. So, in conclusion, in what ways can I apply a Material directive value to a custom set of tags without repeating it in the template?


Solution

  • You can inject MatFormFieldDefaultOptions either on the module level (all fields in given module) or on a component level. It's covered in docs here.

    Here is a stackblitz forked from their demo on form field that changes all the fields in the component.