Home > Net >  how can i edit the contents or the styles of a reused (reusable) component without changing the othe
how can i edit the contents or the styles of a reused (reusable) component without changing the othe

Time:10-03

i have a component called search-footer component which i am using as a search bar and as a footer, i want to change a bit of the content and styles of the footer without affecting the search-bar how can i achieve this?

<app-navbar></app-navbar>
<router-outlet></router-outlet>
<app-search-footer></app-search-footer> //this needes content and styles updating

i use the search-footer component inside the navbar component and in my HomeComponent as you can see

CodePudding user response:

You can update the styles of the child component via the parent component using the following,

  • The ::ng-deep pseudo-class. As applying it to any CSS rule completely disabled view-encapsulation for that rule. In order to scope the specified style to current component and its descendants, add the :host selector before ::ng-deep, as without it the applied styles can bleed to other components.
  • Applying ViewEncapsulation.None inside the component in which the child component is being loaded.

Therefore using the above mentioned approaches, you can modify the styles for app-search-footer as shown in the code snippets below,

  • Using the ::ng-deep pseudo-class,

In the file component.css,

::host ::ng-deep app-search-footer {
  /* Add required CSS rules */
}
  • Using ViewEncapsulation.None

In the file component.ts,

import {
  Component,
  ViewEncapsulation,
  OnInit
} from '@angular/core';

@Component({
      selector: 'app-root',
      templateUrl: '<div class="container"><app-search-footer></app-search-footer></div>',
      styleUrls: ['`.container .app-search-footer-container { /* Required CSS rules */ }`'],
        encapsulation: ViewEncapsulation.None
      }) 
export class Component implements OnInit {

  ngOnInit(): void {
  
  }
}

CodePudding user response:

You can e.g. use Input to control this like

<app-search-footer version='search'></app-search-footer>

In the component:

@Input() version: 'search' | 'footer' = 'footer';

In the component template at the respective spots:

class="some-element {{version}}"

In the css (scss in this case) e.g.:

.some-element {
  &.search {
    background-color: red;
  }

  &.footer {
    background-color: green;
  }
}

How to best do this of course also depends on what needs to be changed (like if it is the whole component or very specific parts of it).
If it is the whole component, you could also simply do <app-search-footer class='search'></app-search-footer>.

There are quite a few ways to accomplish things like this before having to rely on :host ::ngdeep.

  • Related