【问题标题】:Angular 2, component inside main componentAngular 2,主要组件内的组件
【发布时间】:2015-05-21 05:09:26
【问题描述】:

我在 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);

我的组件:

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 = "";
  }
}

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

我的应用模板:

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

那么我该如何连接 User 组件呢?

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

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

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

    • 你是对的,谢谢你的例子。我的应用确实没有指令数组。我的用户组件的模板 url 错误(应该是绝对路径)。而且我没有将组件文件夹添加到 html 文件中的 System.paths 中。
    • 次要问题:我认为您需要在指令列表之前添加一个“常量”。这是一个带有修改后的快速入门教程的微写:bq9.blogspot.ch/2015/03/angular2-dart-nested-components.html
    • @buraq 不,那是飞镖。这个人在用js。
    • 'Foreach, If, CalendarCell' 所有对具体 ng 类的硬引用。如果它们在不同的文件中怎么办?您将需要 DI,在这种情况下您将如何引用它?
    【解决方案2】:

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

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

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

    您可以查看文件名app.appcomponet.ts了解更多详情,希望对您有所帮助。

    【讨论】:

    • 从 RC6 开始,这不可能了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 2017-08-12
    相关资源
    最近更新 更多