“ng g m
{ModuleName}” it will generate the new module in app folder, you can specify a
different path, for example “ng g m modules/{ModuleName}” will generate the new
module in app/modules folder.
For example
“ng g m {ModuleName} --routing” which will also generate routing module with
the new module.
We can
multiple module to implement separation of concern. For example, a side having admin
functionality should have a different module having all the admin site
functionality. We’ll further look into creating new modules in upcoming
articles.
A Component
is a functional code block as a typescript class decorated with @Component(…) decorator having some
metadata which defines a template.
To add a
component you can run the ng command below.
“ng g c
{ComponentName}” it will generate a new component in the default app folder.
“ng g c {path}/{ComponentName}”
you can specify any subfolder to generate in the component. For example, ”ng g c
components/MyNewComponent” command will generate the new component in
“app/components” folder.
Below, is a
very basic component, in which @component decorator is imported from
“@angular/core”. It has two required properties, selector and
template/templateUrl If a component has very simple page content, then “template”
can be used, rather than an HTML file, referenced using templateUrl.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.scss']
- })
- export class AppComponent {
- }
As
AppComponent is the entry point, so it is used as a bootstrap component in the
AppModule. Therefore, we do not need to use the selector anywhere to render it.
Next, let’s
populate this component by adding few properties and method that will then be
used in the template binding.
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.scss']
- })
- export class AppComponent {
- title = 'MyFirstAngular8App';
- backgroundColor = "silver";
- model: any = { username:"adil", firstName:"", lastName:"" }
-
- Submit() {
- console.log('Submited:', this.model);
-
- }
- }
Template
Templates are
the UI elements of the application, which are defined by the Components. To add
extra functionality in a plain HTML file, Angular Templates provide different
types of binding below.
One-way Binding
Interpolation: Allows you to evaluate
an expression and result of the expression is rendered as string.
- <span>{{ title }} app is running!</span>
Property Binding: Allows you to inject
values from app (eg: component) to html, for example injecting a dynamic background
color of a div.
- <div [style.background-color]="backgroundColor"></div>
Or
Setting value
of an input element as a one way binding, specially used for the ready only
field.
- <input type="text" [(value)]="model.username" name="username" readonly>
Event Binding: Allows the app (eg:
component) to respond to a user input, for example button click.
- <button (click)="buttonClick()">click me</button>
Two Way
Binding
ngModel: ngModel as banana in a bracket
“[()]” allows you to send and receive a specific value to html from app and
vice versa. For example UserName field in html form.
- <div [style.background-color]="backgroundColor">
- <span>{{ title }} app is running!</span>
- <br>
- <p> Model json: {{model | json}}
- </p>
- <span>User Name(readonly)</span>
-
- <input type="text" [value]="model.username" name="username" readonly>
- <br>
- <span>First Name</span>
-
- <input type="text" [(ngModel)]="model.firstName" name="firstName">
- <br>
-
- <span>Last Name</span>
- <input type="text" [(ngModel)]="model.lastName" name="lastName">
- <br>
- <button (click)="Submit()">Click me</button>
- </div>
Service (injectable)
If the data or functionality is not view specific, then it can be moved into a service. A Service
provides extra functionality that can be injected into Components through
dependency injection. We can also inject a service in other services. For example, code block for getting/posting form data from/to a Web API, can be moved
to a separate TS class, decorate it as injectable and inject it into a
component.
It is
decorated with @Injectable() decorator from @angular/core.
To add a new
service you can run the command below.
“ng g s {ServiceName}” this
command will generate a new service in app folder.
You can add service in a
different folder, by specifying the path with the service name. For example, “ng g s
services/dataservice” will generate dataservice in
app/services folder.
- import { Injectable } from '@angular/core';
-
- @Injectable({
- providedIn: 'root'
- })
- export class DataService {
- constructor() { }
- }
Let’s add a simple method
“getDefaultObject” which returns an object
And “logObject”
which accepts an object and logs it.
- import { Injectable } from '@angular/core';
-
- @Injectable({
- providedIn: 'root'
- })
- export class DataService {
-
- constructor() { }
-
- getDefaultObject(): any {
- return { username: "adil.khurshed", firstName: "adil", lastName: "khurshed" };
- }
-
- logObject(obj: any) {
- console.log('Submited:', obj);
- }
- }
Now, our service is ready, so
let’s inject it in AppComponent and do some code refactor, to use the service to
get the object and log the object when submitted. To inject a service, we can
simple inject in the constructor, as shown below.
- import { DataService } from './data.service';
- import { Component } from '@angular/core';
-
- @Component({
- selector: 'app-root',
- templateUrl: './app.component.html',
- styleUrls: ['./app.component.scss']
- })
- export class AppComponent {
- title = 'MyFirstAngular8App';
- backgroundColor = "silver";
- model: any = {};
- dataServiceObj: DataService;
-
-
- constructor(dataService: DataService) {
- this.dataServiceObj = dataService;
-
- this.model = this.dataServiceObj.getDefaultObject();
- }
- Submit() {
-
- this.dataServiceObj.logObject(this.model);
- }
- }
Conclusion
In this article we have
discussed building blocks of an angular application and created each block with
a basic example.
In the next article, we’ll
discuss Angular Routing in detail, having multiple modules and we will develop a
complex application architecture, with routing.
Git Repository of this article can be found
here.