Archive

Posts Tagged ‘Angular 4’

Angular 4: Understanding Components

If you have followed my previous post on how to use angular-cli to generate an Angular app you may have noticed that it generated AppComponent as the root,in this post we will have a closer look at it to understand what a component is.

The simplest way to define a component is a class which is decorated with an attribute and has an html view which get rendered into the DOM.I have taken the AppComponent example to explain how it compares to a C# class.

Angular Component

It looks pretty close to ASP.NET MVC controller or any C# class with an attribute and it has a view called app.component.html which will get generated into the DOM.

The key thing is the @Component decorator takes a JSON anonymous object in which we specify the template URL and the custom styles to be used for this component. Here is an illustration of this.

Component decorator

And this is how the root component is wired up to the index.html page.

<body>
      <app-root>Loading...</app-root>
</body>

Another interesting thing to notice is that the  component has a property name “title” and by the virtual of the fact that a class is decorated with @Component attribute angular will allow you to bind this property to the view (template) using the double moustache syntax i.e. {{ }} which is also referred to as interpolation.

one way data binding

This is called one-way data binding as the data flows from the object to the view but not both ways, however it is easy to implement a two way by using the [(ngModel)] syntax as shown below.

<h1>
  {{title}}
</h1>
<input [(ngModel)]="title" />

After saving your changes and the page has refreshed if you type anything in the text box it will be immediately be reflected in the h1 header as shown below.

Two way data binding

I hope this post has helped you if you are coming from a non angular background and to understand how thing works in angular.

Advertisements