简体   繁体   中英

routerLink outside of component template in Angular 2, in base html

When I use the routerLink directives inside my @Component 's template property, it works.

But we're talking about my entire sites top menu bar. But when I separate it out into my main template file (layout.html), it no longer functions.

Yeah im a huge noob to ng2, admittedly, but I'd like my menu to stay out of a javascript file and inside the main layout html. How can one accomplish this?

<body>
    <base href="/" />
    <div class="row menu">
        <div class="container">
            <ul class="u-pull-left">
                <li><a [routerLink]="['/']" routerLinkActive="active">Home</a></li>
                <li>Notifications</li>
                <li>My Hisses</li>
            </ul>
            <ul class="u-pull-right">
                <li><a [routerLink]="['/register']" routerLinkActive="">Register</a></li>
                <li><a [routerLink]="['/login']" routerLinkActive="active">Login</a></li>
            </ul>
        </div>
    </div>

  <root></root>
<!-- End Document
  –––––––––––––––––––––––––––––––––––––––––––––––––– -->
</body>

Which vital step am I missing? Is it even possible?

Thank you!

routerLink is a directive and [routerLink]="..." is a binding to the input of a directive. None of these are supposed to work outside of an Angular2 component.

You can use a shared service that is instantiated outside of Angular2 and passed as a provider

 let service = new MyService();

 @NgModule({
   providers: [{provide: MyService: useValue: service}],
   ...
 })
 class AppModule {}

then you can use service to communicate with some Angular2 component or service to delegate calling router.navigate(...) do do imperatively what routerLink would do.

Another way is firing events ( window.dispatchEvent(...) ) and listening for this events inside Angular2.

If possible I'd avoid such a setup (having router links outside Angular2 components) entirely.

You cannot do this because routerLink is special angular2 syntax that gets transpiled down to js and your template HTML is the bootstrap of the application and does not get transpiled .

Typically what you would do to accomplish a static top bar is to create a new topbar component and use it as a directive in your parent app above where you call your router outlet.

Example. In your app.component. you would import your component

Import {TopNav} from 'topnav.component '

@Component({ selector : 'my-app', template : , directives: [TopNav] })

Your topnav component would contain your routing logic

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