Angular 2,主要组件内部的组件

use*_*512 26 angular

我在angular.io上玩过angular 2演示.现在我想创建一个新组件并在我的应用程序中使用它.

我目前的应用:

import {Component, Template, bootstrap} from 'angular2/angular2';
import {UsersComponent} from './components/users/component.js';

// Annotation section
@Component({
  selector: 'my-app'
})
@Template({
  url:"app.html"
})
// Component controller
class MyAppComponent {
  newName:string;
  names:Array<string>;
  constructor() {
    this.name = 'Florian';
  }

  showAlert(){
    alert("It works");
  }

  addName(){
    names.push(newName);
    newName = "";
  }
}

bootstrap(MyAppComponent);
Run Code Online (Sandbox Code Playgroud)

我的组件:

import {Component, Template, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
  selector: 'users'
})
@Template({
  url:"./template.html"
})
// Component controller
class UsersComponent {
  newName:string;
  names:Array<string>;
  constructor() {

  }

  addName(){
    names.push(newName);
    newName = "";
  }
}
Run Code Online (Sandbox Code Playgroud)

我不确定我的用户组件的语法是否正确.

我的app模板:

<h1>Hello {{ name }}</h1>
<h2>{{2+2}}</h2>
<hr />
<button (click)="showAlert()">Click to alert</button>
<users></users>
Run Code Online (Sandbox Code Playgroud)

那么如何连接用户组件?

我在控制台中遇到的错误:

 "Error loading "components/users/component.js" at <unknown>?Error loading "components/users/component.js" from "app" at http://localhost:8080/app.es6?Cannot read property 'replace' of undefined"
Run Code Online (Sandbox Code Playgroud)

use*_*449 25

角度日历演示有两个嵌套组件(日历和日历单元格) https://github.com/djsmith42/angular2_calendar.git.从我可以看到你的MyAppComponent应该从@ Template的指令列表中引用Users组件,如下所示:

@Template({
  url: System.baseURL+'app/components/calendar/calendar.html',
  directives: [
    Foreach,
    If,
    CalendarCell
  ]
})
Run Code Online (Sandbox Code Playgroud)


Ang*_*gel 11

在这个Angular2web https://angular.io/docs/ts/latest/tutorial/toh-pt3.html#的链接中你可以看到添加directives: [...]内部@Components例如:

@Component({
  selector: 'my-app',
  directives: [UsersComponent]
})
Run Code Online (Sandbox Code Playgroud)

但是否则链接使用组件内部的模板,如果使用@Template({ url:"app.html"})外部组件,则不知道这是否有效.

您可以查看文件名app.appcomponet.ts以获取更多详细信息,希望有所帮助.

  • 从RC6开始,这是不可能的. (3认同)