Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css class not taking effect after changing nativeElement.className

So I'm writing an angular app and I'm trying to re-style a mat-form-field.

HTML:

<mat-form-field  #matFormField class="example-full-width" >
     <input #autocompleteInput type="text" placeholder="Enter {{searchBy.value}}" aria-label="Number" matInput [formControl]="myControl"
         [matAutocomplete]="auto"  (keyup.enter)="onEnter()">
     <fa-icon  [icon]="faSearch"></fa-icon>
     <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
         <mat-option *ngFor="let option of autocompleteList" [value]="option" (onSelectionChange)="autocompleteSelected($event)">
             {{option[searchBy.value]}}
         </mat-option>
     </mat-autocomplete>
</mat-form-field>

Typescript:

@ViewChild('matFormField', { static: false, read: ElementRef}) formField: ElementRef;

ngAfterViewInit(): void {
  this.formField.nativeElement.children[0].children[0].children[0].className = 'mat-form-field-infix-fix';
}

SCSS:

mat-form-field {
  width: 100%;
}

.mat-form-field-infix-fix {
  display: flex;
  position: relative;
  flex: auto;
  min-width: 0;
}

fa-icon {
  float: right;
}

and I can see that the className is definitely applied:

screen capture of web developer tools inspecting div showing div.mat-form-field-infix-fix

but for some reason the css isn't:

missing css in developer tools

Does anybody know what's going on here?

like image 646
Peter Weeks Avatar asked May 20 '26 20:05

Peter Weeks


1 Answers

I believe you're running into View Encapsulation discussed here. Notable points:

As discussed earlier, component CSS styles are encapsulated into the component's view and don't affect the rest of the application.

And the earlier discussion in the Style Scope section:

The styles specified in @Component metadata apply only within the template of that component.

They are not inherited by any components nested within the template nor by any content projected into the component.

So, to get your css to effect a nested components styling you have a few options:

  1. Change the view encapsulation setting
  2. Put this styling in the global style sheet of your application
  3. In the component's css, use special piercing rules such as ::ng-deep (useful, but Angular team has deprecated these without providing a good alternative)
like image 101
Frederick Avatar answered May 23 '26 15:05

Frederick