Search code examples
angulardynamicstyles

dynamically style component containing third-party component depending on context angular


Edit: the difficult thing here is that I can't change the class of the third party component. I need to add styles to the class mat-form-field-wrapper dynamically, which is part of a third-party (angular material) component

So let's say I have a component, "app-search-bar", which contains an angular-material "mat-form-field" that I want to style a particular way depending on where the search bar appears in my app. I know I can style third-party components using ::ng-deep and the !important flag but is there any way for me to apply such styles dynamically in different contexts?

What I'd like is a way to do something like this:

search-bar.component.ts:

    export class SearchBarComponent {
      @Input() styles;

search-bar.component.scss

    ::ng-deep .mat-form-field-wrapper {
      width: styles.width;
    }

Solution

  • One thing that i do i define a class for each scenario and take the class from input component. Example:

    @Input() elClass = "my-default-class";
    

    And then in the template

    <child-component [class]="elClass">...
    

    And in styles:

    child-component.my-default-class ::ng-deep {}
    child-component.another-class ::ng-deep {}