Search code examples
cssangularangular-material2

angular 5 material - form fields stuck at 180px


I've created a form in a dialog using material forms, but I can't seem to get the inputs to be wider than 180px despite following numerous examples including https://material.angular.io/components/input/example.

I'm sure this is a pretty standard CSS thing, but I don't have that sort of brain so I cant figure out the problem.

Does anyone have a serious / non-trivial example that works??

Here's mine:

<h1 mat-dialog-title>{{title}}</h1>
<mat-dialog-content>
  <form novalidate #f="ngForm" class="form-full-width">
    <mat-form-field class="input-full-width">
      <input type="text" [(ngModel)]="data.name" name="name" matInput placeholder="Name">
      <mat-hint>Enter a unique name.</mat-hint>
    </mat-form-field>
    <mat-form-field class="input-full-width">
      <textarea [(ngModel)]="data.description" name="description" matInput placeholder="Description"></textarea>
      <mat-hint>You should describe the purpose/use of this thing.</mat-hint>
    </mat-form-field>
  </form>
</mat-dialog-content>

CSS :

.form-full-width {
    min-width: 150px;
    max-width: 500px;
    width:100%;
}

.input-full-width {
    width:800px;
}

.mat-form-field.mat-form-field {
    width: auto;
}

Thanks.


Solution

  • Seems like it's something to do with View Encapsulation. This thread explains it: https://github.com/angular/material2/issues/4034 but changing encapsulation for the component causes all sorts of compile failures.

    This article gave me the correct solution:https://material.angular.io/guide/customizing-component-styles

    I'll move my style to global scope...

    .formFieldWidth480 .mat-form-field-infix {
       width: 480px;
    }
    

    and in the component that opens the dialog:

    this.newDialog = this.dialog.open(NewDialogComponent,
      {
        width: '650px', height: '550px',
        data : newThing,
        panelClass : "formFieldWidth480"
      });
    

    I hope this saves someone else the day I lost...