简体   繁体   中英

Angular2: replace component element entirely

I was looking around for a while now and cannot seem to find the right answer... this should be something very trivial... and be documented everywhere... just seems cannot find it...

so, I have a very, very easy component/directive called navItem

This is how I call it

<ul>
    <nav-item route="/aboutus">About us</nav-item>
    <nav-item route="/contactUs">Contact us</nav-item>
</ul>

and this is what is inside it (nav-item.html):

<li><a [routerLink]="route"><ng-content></ng-content></a></li>

so basically I have just this:

import { Component, Input } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';

@Component({
    moduleId: module.id,
    selector: 'nav-item',
    template: require('./nav-item.html'),
    directives: [ROUTER_DIRECTIVES]
})
export class NavItem {
    @Input() route = '/';


    constructor(){}
}

What I get is

<ul>
    <nav-item _ngcontent-xng-6="" route="/aboutus" ng-reflect-route="/aboutus"><li><a ng-reflect-router-link="/aboutus" ng-reflect-href="/aboutus" href="/aboutus">About us</a></li></nav-item>
    <nav-item _ngcontent-xng-6="" route="/contactus" ng-reflect-route="/contactus"><li><a ng-reflect-router-link="/aboutus" ng-reflect-href="/contactus" href="/contactus">Contact us</a></li></nav-item>
</ul>

Which of course I don't want.

What I want is replacing <nav-item> </nav-item> entirely with <li><a></a></li>

In AngularJs that was very simple.

This is not supported and I'm pretty sure it won't be in the future. replace: true was deprecated also in Angular1 since quite some time.

What you can do is using attribute selectors like

@Component({
    moduleId: module.id,
    selector: '[nav-item]',
    template: require('./nav-item.html'),
    directives: [ROUTER_DIRECTIVES]
})
export class NavItem {
    @Input() route = '/';


    constructor(){}
}
<a [routerLink]="route"><ng-content></ng-content></a>

and use it like

<ul>
    <li nav-item route="/aboutus">About us</li>
    <li nav-item route="/contactUs">Contact us</li>
</ul>

我认为您想要的是属性指令,而不是上面建议的组件。

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