【问题标题】:Angular 2 how to use nested componentsAngular 2 如何使用嵌套组件
【发布时间】:2016-08-04 11:12:08
【问题描述】:

我刚开始使用 Angular 2,在使用组件时遇到了问题。我想在“MyApp”组件的模板中使用“NavigationComponent”组件。

这是“MyApp”组件(/app/app.component.ts):

import { Component } from 'angular2/core';
import { RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from 'angular2/router';
import {NavigationComponent} from './navigation/navigation.component';

@Component({
    selector: 'my-app',
    templateUrl: 'app/app.component.html'
})
export class MyApp {
}

/app/app.component.html:

<nav class="pink accent-3" role="navigation">
    <na-navigation>Loading...</na-navigation> // <-- this is my not working attempt :(
</nav>
<footer class="page-footer">
    <!--footer-->
</footer>

/app/navigation/navigation.component.ts:

import { Component, OnInit } from 'angular2/core';
import { MenuItem } from './menuItem';

@Component({
  selector: 'na-navigation',
  templateUrl: 'app/navigation/navigation.component.html'
})
export class NavigationComponent implements OnInit {

  menuItems: MenuItem[] = [];

  ngOnInit() {
      this.menuItems.push(new MenuItem("Sign in", "signIn"));
      this.menuItems.push(new MenuItem("Create account", "createAccount"));
  }
}

/app/navigation/navigation.component.html:

<div class="nav-wrapper container">
    <a id="logo-container" href="#" class="brand-logo">Logo</a>
    <ul class="right hide-on-med-and-down">
        <li *ngFor="#menuItem of menuItems">
            <a>{{menuItem.label}}</a>
        </li>
    </ul>
</div>

但最后我的标签没有渲染,而不是菜单列表,只有“正在加载...”。

我应该如何将“NavigationComponent”传递给“MyApp”以便在“app.component.html”模板中可用?

【问题讨论】:

    标签: javascript typescript angular


    【解决方案1】:

    您需要在directives: [] 数组中列出您在模板中使用的所有组件和指令。

    @Component({
        selector: 'my-app',
        directives: [NavigationComponent],
        templateUrl: 'app/app.component.html'
    })
    export class MyApp {
    }
    

    如果组件的代码在同一个文件中,请确保您不要引用文件中更靠后的类,因为这样在您使用它们时它们是未知的。 TypeScript 中的类不会被提升。

    如果您每个班级有一个文件,那么您是安全的。

    【讨论】:

      猜你喜欢
      • 2017-02-14
      • 2017-03-01
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-07-20
      相关资源
      最近更新 更多