【问题标题】:When is a directive required in component metadata in Angular2?Angular2 的组件元数据中何时需要指令?
【发布时间】:2016-09-10 04:45:31
【问题描述】:

在此处找到的角度教程中: https://angular.io/docs/ts/latest/tutorial/toh-pt3.html

HeroDetailComponent 作为指令添加到 app.component.ts:

@Component({
    selector: 'my-app',
    //...
    directives: [HeroDetailComponent]
})

教程说: “浏览器会忽略它无法识别的 HTML 标记和属性。Angular 也是如此……我们通过在元数据指令数组中列出它来告诉 Angular(HeroDetailComponent)。”

但是在此处找到的工作示例中: https://github.com/DeborahK/Angular2-GettingStarted(参见 APM - 最终更新项目)

app.component.ts 加载一个名为 ProductDetailComponent 的组件,但它没有指令:

@Component({
    selector: 'pm-app',
    //...
    directives: [ROUTER_DIRECTIVES],    
})

为什么第二个示例能够在没有 ProductDetailComponent 指令的情况下加载 ProductDetailComponent?

【问题讨论】:

    标签: angular angular2-directives


    【解决方案1】:

    据我所知,AppComponent 导入 ProductDetailComponent 但通过 <router-outlet> 使用它,因为 ProductDetailComponent 是在 @Routes 中定义的。

    这意味着<router-outlet> 只定义了当您决定导航到组件时将显示的位置(在这种情况下发生在执行代码<a [routerLink]="['/product', product.productId]"> 出现在product-list.component.html强>)。

    ProductListComponent 没有定义任何selector,因此无法在任何其他组件的模板中引用。

    组件需要在其指令中定义通过其选择器在其模板中引用的组件/指令。

    希望对你有帮助

    【讨论】:

    • >> 我希望这会有所帮助。确实如此。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2017-11-05
    • 2017-01-31
    • 2016-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 1970-01-01
    • 2016-10-19
    相关资源
    最近更新 更多