javascript - 子组件未在主组件中以 Angular 呈现。当我点击按钮时它会单独渲染

标签 javascript angular angular-routing

我有一个名为 main-header 的主要组件,其中有一个菜单,其中包含三个标记为“桌面”、“Web”和“移动”的按钮。当我单击菜单按钮时,它会在新屏幕中呈现,但我想在新屏幕中呈现我的主要组件是 main-header。

ma​​in-header.component.html

<div class="main-header">
    <h1>{{appTitle}}</h1>
    <button type=""><a routerLink="/main-header/desktop">Desktop</a></button>
    <button type=""><a routerLink="/main-header/web">Web</a></button>
    <button type=""><a routerLink="/main-header/mobile">Mobile</a></button>
</div>
<router-outlet></router-outlet>

desktop.component.html

<p>
  desktop works!
</p>

app.routes.ts

import {ModuleWithProviders} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';

import {MainHeaderComponent} from './containers/main-header/main-header.component';
import {DesktopComponent} from './containers/desktop/desktop.component';
import {WebComponent} from './containers/web/web.component';
import {MobileComponent} from './containers/mobile/mobile.component';


export const router: Routes =[
    {path: '', redirectTo:'main-header', pathMatch: 'full'},
    {path: 'main-header', children:[
        {path:'', component:MainHeaderComponent, pathMatch:'full'},
        {path: 'desktop', component:DesktopComponent},
        {path: 'web', component: WebComponent},
        {path: 'mobile', component: MobileComponent}
    ]}
];

export const routes: ModuleWithProviders = RouterModule.forRoot(router);

最佳答案

当您需要时,组件会显示它,而不是路由。

<div class="main-header">
    <h1>{{appTitle}}</h1>
    <button type=""><a href="javascript: void(0)"(click)="changeBoolean()">Desktop</a></button>
</div>
<child-compoent *ngIf="istrue()"></child-component>

父组件将具有如下内容:

export class ParentComponent {

  private showComponent = false;

  constructor() { }

  public changeBoolean() {
    this.showComponent = true;
  }

  public isTrue() {
    return this.showComponent;
  }

关于javascript - 子组件未在主组件中以 Angular 呈现。当我点击按钮时它会单独渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43849055/

相关文章:

javascript - 如何将动态复选框值绑定(bind)到对象上的 Knockout observableArray?

angular - 使用 NgRx 加载子路由

javascript - 使用过滤数据时,ion-select 不会呈现选定值

Angular - 测试 Routerguard

angular - 不同的路线,相同的组件 - 为什么组件不在路线更改时重新加载?

javascript - 使用 multer-s3-transform 保留原始文件

javascript - 如何确保只有我自己的网站(客户端代码)可以与 Firebase 后端对话?

javascript - 将点击功能添加到动态创建的下拉列表中

html - 无法使用表中的列数组迭代 *ngFor 循环

javascript - Angular2 管道中的新关键字