Site icon CodePortal

Creating Component in Angular2

In last post Starting with Angular2 we have learned installing angular-cli and starting server. In this post we’ll create simple Angular2 Component using angular-cli. So let’s start.

Get code from Github: Angular2 Basics

So we’ll be using the same directory which we’ve used in last post. Open terminal tab in that directory and run following command (make sure app is running in other terminal window):

ng generate component form --inline-template --inline-style


ng g c form -it -is

g — generate

c — component

form — {{component_name}}

it — inline-template

is — inline-style


This will generate two files: Component file and Component spec file inside src/app/{{component_name}}/ directory.

Let’s see what’s inside component file — form.component.ts

selector: 'app-form',
template: `
form Works!`,
styles: []

So we have component’s selector here which is app-form.

Let’s use this selector in app component file — app.component.ts

So new code will be like this,

selector: 'app-root',
template: '',
styles: []

Now your browser should auto refresh and it should display this:


Alright then, now you try to play with this component via changing templates or instead of using inline template, use templateUrl and link to html file!


Get code from Github: Angular2 Basics

Exit mobile version