简体   繁体   中英

Angular 2 way for creating wrapper component

In my angular 2 redux app for root component I use next template:

<div class="app">
  <custom-header></custom-header>
  <router-outlet></router-outlet>
  <custom-footer></custom-footer>
</div>

So, I have the same header and footer on every route. And I would like to create something like this for every app component: some container which will add some common styles for every page (for example: panel with custom title and page custom html). In React for this I could create next components:

const CustomWrapper = ({ title, sidebar, children }) => (
  <div>
    <h2>{title}</h2>
    { sidebar &&
      <div className="sidebar">{sidebar}</div>
    }
    <div style={{some condtitional styles}}>{children}</div>
  </div>
);

and then

const SidebarPage = () => (
  <CustomWrapper
    title="Title from state or"
    sidebar={<div>JSX template for sidebar</div>}
  >
    <div>JSX template for page content</div>
  </CustomWrapper >
)

and use SidebarPage for some route. So, CustomWrapper can be used for every page for same styling and has custom parts according to props and some conditions.

What is angular 2 way for this case?

You can create Header and Footer components that take in @Inputs from the main component, or you can update them with services depending on the route you take.

@Component{}
export class Header implements OnInit {

    constructor(private myService: RouteChangedService){}

    ngOnInit(){
        this.myService.routeUpdated().subscribe(data => { this.updateView(data) } )
    }
}

In this manner you can have a constant header and footer like you had above:

<header></header>
<router-outlet></router-outlet>
<footer></footer>

And call routeUpdated on component instantiation to inform them of the new route and to update their views and logic accordingly. You may also be able to leverage the router to call these services based on route name, but I haven't done that myself.

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