Angular 2如何使用嵌套组件

时间:2016-04-13 11:29:16

标签: javascript typescript angular

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

这是" 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>

但最后我的标签没有呈现,而不是菜单列表,只有&#34;正在加载...&#34;。

我应该如何通过&#34; NavigationComponent&#34;进入&#34; MyApp&#34;在&#34; app.component.html&#34;模板?

1 个答案:

答案 0 :(得分:1)

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

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

如果组件的代码位于同一文件中,请确保不要引用文件中较低级别的类,因为在使用它们时它们是未知的。 TypeScript中的类不会被挂起。

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