Get me out of the Angulars css-hell! (seeks a css-fix strategy)

Viewed 33

Since my first program in 1980, I feel that I am more of a user than a programmer. That is a good thing. Angular is a great example. I don't need to know its inner workings to create acceptable code. Unless a textarea is rendered a bit too narrow, as I am fighting right now.

Angular documents it as follows: Avoid defining custom styles that would affect the size or internal layout of the component I could read it ten times but it is too complicated for a programming user of Angular Material.

Then I google and find solutions here that may have worked in other versions, but not for me today.

What I need is a strategy to get my CSS working. Do you have a suggestion?

3 Answers

if you want to override the Angular Material UI, one of the simplest way is to define the css in the main styles.scss (not the one in the component) i.e:

mat-form-field {

  &.my-class {
    width: 100%;
  }

}
<mat-form-field class="my-class">
  <mat-label>My Textarea</mat-label>
  <textarea matInput></textarea>
</mat-form-field>

sometimes you need to have a more specific rule or us !important

Zerotwelves solution that worked for me. Component:

    <mat-grid-tile colspan="3" rowspan="3">
        <mat-form-field class="myTextArea" [formControl]="control">
            <textarea
                      #textArea
                      matInput
                      [(ngModel)]="data.text"
                      (keyup.enter)="sendTweet(data)"
                      (keyup)="showAuto($event)"
                      [matAutocomplete]="auto"
            ></textarea>

Removed: style="width: 40vw;" from the components css and its html.

Added to the global styles.css:

.myTextArea {
    width: 40vw;
}

Depends upon the component that you are trying to change styles of. For example, for simple properties of mat-form-field you can simple add the CSS in the same component or use a bootstrap class directly on it.

account.component.html

<mat-form-field class="w-100 or-your-class">
  <mat-label>
    <i class="fcp fcp-envelope mr-1"></i>Account Email
  </mat-label>
  <input type="email" matInput class="text-dark" formControlName="accountEmail" required>
</mat-form-field>

account.component.css

.or-your-class{
  margin-bottom: 5px;
}

But there are HTML Elements that are created beyond that components "scope", to apply the styles to those HTML Elements either you can turn off ViewEncapsulation (not recommended) or You can add the styles in your top most .css file which is usually the styles.css as well as using !important to override the styles of that Material UI Component

Related