Angular 2 set default content in the router-outlet

2020-03-01 19:59发布

问题:

I want to set some default text inside the router-outlet until it is populated.

I have a parent component that will display the child route component within the router-outlet on that page.

There are 2 buttons that will populate the router-outlet with the child component when clicked. How can i place content inside the router outlet eg. 'Click an options to display the data' then once the button is clicked this message clears and the child component displays in the router outlet?

<div class="container pt-3">
    <div class="clearfix">
        <div class="btn btn-outline-success float-left"
            routerLink="/unpaid/people">
            View People
        </div>
        <div class="btn btn-outline-success float-right"
            routerLink="/unpaid/bills">
            View Bills
        </div>
    </div>
</div>
<router-outlet>Click an options to display the data</router-outlet>

EDIT here are my routes

path: 'unpaid', component: UnpaidBillsComponent,
    children: [
      {path: 'people', component: UnpaidPeopleComponent},
      {path: 'bills', component: UnpaidBillListComponent}
    ]

回答1:

default text inside the router-outlet until it is populated

Firstly, your assumption here is wrong, content is not inserted inside the outlet, but below it.


You cannot set a default content in the template, but you can set the default route which contains your default content. Simply use path: '' and use a component with your "default" template.


Create a component with the "default" template you need:

@Component({template: `Default template here`})
export class DefaultTemplateComponent {}

And add it to your routes.

children: [
  {path: '', component: DefaultTemplateComponent},
  {path: 'people', component: UnpaidPeopleComponent},
  {path: 'bills', component: UnpaidBillListComponent},
]


回答2:

In Template:

<p *ngIf="showDefaultMessage">Click an options to display the data</p>
<router-outlet (activate)="toggleDefaultMessage(false)" (deactivate)="toggleDefaultMessage(true)"></router-outlet>

then in Component just toggle "showDefaultMessage" property:

private showDefaultMessage = true; // default state

toggleDefaultMessage(state: boolean) {
    this.showDefaultMessage = state;
}


回答3:

children: [
  {path: '', redirectTo: '/people', pathMatch: 'full'},
  {path: 'people', component: UnpaidPeopleComponent},
  {path: 'bills', component: UnpaidBillListComponent}
]


回答4:

<div class="col-sm-10">
<router-outlet></router-outlet>
<a routerLink="/" routerLinkActive #rla="routerLinkActive" 
   [routerLinkActiveOptions]="{exact:true}">
  <h5 *ngIf="rla.isActive" class="beauty">Click on any button to start!</h5>
</a>
</div>

https://angular.io/api/router/RouterLinkActive



标签: angular