typescript - 当前组件后的angular 2附加指令

标签 typescript angular

假设我有以下示例组件(注意 my-app 不是在 index.html 中使用的应用程序定义组件)

@Component({
    selector: 'my-app',
    directives: [NavbarComponent, SidebarComponent],
    template: `
      <my-navbar></my-navbar>
      <router-outlet></router-outlet>
      <my-sidebar></my-sidebar> <!-- Append this after <my-app></my-app> -->
    `
})

我希望能够并使用 <my-sidebar>组件并向其添加信息,但是我想在 <my-app> 之后显示它而不是在里面。这在 Angular 2 中完全可能吗?

最佳答案

正常创建侧边栏组件

@Component({
  selector: 'my-sidebar',
  template: 'Sidebar'
})
class SidebarComponent{}

然后在你的AppComponent你可以使用 DynamicComponentLoader注入(inject) SidebarComponentAppComponent 旁边

@Component({
  selector: 'my-app',
  directives: [NavbarComponent, ROUTER_DIRECTIVES],
  template: `
    <my-navbar></my-navbar>
    <router-outlet></router-outlet>
})
class AppComponent {
    constructor(dcl: DynamicComponentLoader, elementRef: ElementRef) {
        dcl.loadNextToLocation(SidebarComponent, elementRef);
    }
}

最终结果会是

<my-app>
  <my-navbar></my-navbar>
  <router-outlet></router-outlet>
</my-app>
<my-sidebar>Sidebar</my-sidebar>

关于typescript - 当前组件后的angular 2附加指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35071426/

相关文章:

angular - 为什么不将 ngClass 类参数添加到 html 标签中,但 Angular 模板中的条件为 true?

angular - 自定义订阅错误 Angular

typescript - 在将新记录插入 typescript 中的其他模型之前检查 Sequelize 模型中的值

html - Angular:在日期字段的输入类型文本中添加斜杠 "/"

javascript - Angular 8 组件更改和 ngOnInit 调用

javascript - Angular 6 : not set properties of class after calling HTTP-request

通用 typescript 将下划线对象转换为驼峰式大小写

typescript - 调用方法表单 setInterval() 导致异常

html - 页面在 IE11 上的显示方式问题

angular - 在 Angular 中从不同的本地主机获取数据