【问题标题】:One common button provided in angular parent component to be used by nested childrenAngular 父组件中提供的一个常用按钮,供嵌套子级使用
【发布时间】:2018-05-28 23:34:43
【问题描述】:

Angular 应用的路由如下:

componentRoutes: Routes = [
    {path: 'child',
    canActivate: [guardService],
    component: ParentComponent,
    children: [
        {path: '', component: nestedChildComponent1},
        {path: ':id', children: [
            {path: 'child2', component: nestedChildComponent2},
            {path: 'child3', component: nestedChildComponent3},
        ]},
    ]
},
];  

Parent组件如下:

@component({
  template: <div>
                <H3> This is Parent Component </H3> 
                <button id='button' (click)="buttonClickedHandler()"> click me </button>
            </div>
            <router-outlet></router-outlet>   <--- nested child components go here
})
export class ParentComponent implements OnInit, OnDestroy {
...
}  

ParentComponent 中的按钮在所有嵌套路由中是通用的。每个嵌套的子组件都必须为buttonclickedHandler 提供自己的实现。我该怎么办?我的嵌套组件应该扩展 ParentComponent 还是应该实现一个提供buttonclickedHandler 抽象 API 的接口?

我提到了abstract method in typescriptcreating interfaces for angular services 的帖子,我很困惑如何解决我的问题。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    可能有很多方法并且都是有效的。我的处理方式: ParentComponent 提供带有 Subject 的服务。
    ChildComponents 都扩展了一个需要这个服务的抽象类

    父组件中的buttonClickHandler在Subject上调用.next ChildComponents 订阅了这个 Subject

    【讨论】:

    • 有没有办法在不使用服务的情况下达到同样的效果?
    • 我对此并不积极,因为它们位于路由器插座中,但如果您可以使用 ViewChildren 或 ViewChild 找到它们,那么您可以将它们类型转换为具有调用功能的接口。所以像 IChildComponent 必须有一个名为 clickHandler 或类似的函数
    猜你喜欢
    • 2018-08-23
    • 2017-09-16
    • 2018-04-27
    • 2020-04-05
    • 2019-03-27
    • 1970-01-01
    • 2020-10-25
    • 2018-07-30
    • 2018-05-25
    相关资源
    最近更新 更多