简体   繁体   中英

How To Add CSS to router-outlet element

I have some code that looks like this:

  <section>
    <div style="height: 100%; max-width: 10%; background-color: deepskyblue;">my content</div>
    <router-outlet style="height: 100%; min-width: 90%; background-color: gold;"></router-outlet>
  </section>

I want the div to work as a side-bar with the router-outlet taking up the remaining 90% of the space. But what ends up happening is that the content displayed from the router-outlet is pushed beneath the div rather than beside it. It also appears that no CSS is being applied to the router-outlet, as the background color doesn't change. Is there any way to get CSS to make changes to this router-outlet?

simple solution is to to just put router-outlet in a style div.

 <section> <div style="height: 100%; max-width: 10%; background-color: deepskyblue;">my content</div> <div style="height: 100%; min-width: 90%; background-color: gold;"> <router-outlet ></router-outlet> </div> </section>

Short answer Use:

:host { background: cornflowerblue; }

as the css for the hosted component, to change background of the router outlet.


Long Answer: Angular CSS pseudo selector/modifier You can affect the hosting component with the:host modifier. In the case that you would like to change the router oulet styling, add css to the component that will be hosted.

eg Change the router outlet blue when showing the page-edit component.

// This is your routing to place your page component in the outlet when 
navigating to the edit/1 url.

const routes: Routes = [
  {
    path: 'edit/:pageId',
    component: PageComponent,
  }
];

@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})

export class PageEditorRoutingModule {}

// PageComponent - stub of component to be rendered in outlet.
@Component({
  selector: 'app-page-editor',
  templateUrl: './page-editor.component.html', //implement as desired.
  styleUrls: ['./page-editor.component.scss']
})
export class PageEditComponent {
  // Your implementation
}

// Put this in your page-editor.component.scss to change the router outlet background blue
:host{
  background: cornflowerblue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM