简体   繁体   English

Angular2创建一个组件

[英]Angular2 Create a component

I wanted to create a new component in angular2 with specific properties so I can have a tag to use as this 我想在angular2中创建一个具有特定属性的新组件,因此可以使用一个标签

<my-cmp type="Type1"></my-cmp>

I tried many examples but no one of them worked. 我尝试了许多示例,但没有一个起作用。 If anyone has any working example please help me thank you. 如果有人有任何可行的例子,请帮助我,谢谢。

Thanks Khaled 谢谢哈立德

You can play with my test repository (made for a presentation I made about preparations for Angular 2.0) 您可以使用我的测试库 (为我所做的有关Angular 2.0的准备所做的演示而制作)

Hope it helps... 希望能帮助到你...

EDIT 编辑

Another interesting resource is a playground repository that I created, experimenting ngUpgrade. 另一个有趣的资源是我创建的游乐场存储库 ,正在尝试ngUpgrade。 This feature is not bublic, yet, for current Angular 2.0 version (alpha 45), but I am demonstrating the use of it by importing the module from Angular's source code. 对于当前的Angular 2.0版本(alpha 45),该功能尚未公开,但是我通过从Angular的源代码中导入模块来演示其使用。

Here you are. 这个给你。 See this plunker . 这个笨蛋 Written in TypeScript: 用TypeScript编写:

import {Component, Input} from 'angular2/angular2'

@Component({
  selector: 'my-cmp'
  template: `
    <div>
      <b>Type:</b> {{ type }}
    </div>
  `
})
class MyComponent {
  @Input() type;
}

@Component({
  selector: 'my-app',
  directives: [MyComponent],
  template: `
    <my-cmp type="Static Type"></my-cmp>
    <my-cmp [type]="dynamicType + dynamicTypeIndex"></my-cmp>
  `
})
export class App {
  dynamicType: string = 'Dynamic Type ';
  dynamicTypeIndex: number = 0;

  constructor() {
    setInterval(() => ++this.dynamicTypeIndex, 1000);
  }
}

The simplest answer is @Component annotation convert any typescript class to a angular2 component. 最简单的答案是@Component注释,将任何打字稿类转换为angular2组件。 Any typescript class annotated as @Component({}) is angular2 component. 任何标注为@Component({})的打字稿类都是angular2组件。 As you can see in the previous answer, 2 classes are annotated with @Component. 正如您在前面的答案中看到的那样,两个类都用@Component注释。 The Component takes a json object as parameter to tell angular2 what behavior of the component will be. 组件将json对象作为参数来告诉angular2组件的行为。

   @Component({
      selector: 'my-app',   //will be user in html as tag/attribut
      template: `   //the html injection etc
        <my-cmp type="Static Type"></my-cmp>
        <my-cmp [type]="dynamicType + dynamicTypeIndex"></my-cmp>
      `
    })
    export class AppCompoment {   //we exported this class/component so that it can be imported

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM