Khalifa
Khalifa

Reputation: 313

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

<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

Upvotes: 1

Views: 182

Answers (3)

Reese Davis
Reese Davis

Reputation: 147

The simplest answer is @Component annotation convert any typescript class to a angular2 component. Any typescript class annotated as @Component({}) is angular2 component. As you can see in the previous answer, 2 classes are annotated with @Component. The Component takes a json object as parameter to tell angular2 what behavior of the component will be.

   @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

    }

Upvotes: 0

Yaniv Efraim
Yaniv Efraim

Reputation: 6713

You can play with my test repository (made for a presentation I made about preparations for Angular 2.0)

Hope it helps...

EDIT

Another interesting resource is a playground repository that I created, experimenting 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.

Upvotes: 2

alexpods
alexpods

Reputation: 48505

Here you are. See this plunker. Written in 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);
  }
}

Upvotes: 2

Related Questions