Angular 4: Generating Components and How to Use

To create a new component in Angular 4 automatically with the Angular CLI, in the projects root directory type,

$ ng generate component my-component

Where ‘my-component’ is the name of the component. The commands ‘generate’ and ‘component’ can respectively be replaced with ‘g’ and ‘c’. The following command does the same as the above command,

$ ng g c my-component

This will create a new folder in the app directory with the following files,

The command also makes changes to the file src/app/app.module.ts on lines 7 and 12,

Also the file src/app/my-component/my-component.component.ts is created as follows,

These changes could all be implemented manually instead of using the command.

To create a new component without the src/app/my-component/my-component.component.spec.ts which is for unit unit testing,

$ ng g c my-component –spec false (Note: before the spec there are two hyphens)

my-component.component.ts contains

templateUrl: ‘./my-component.component.html’,

to use the contents of srcv/app/my-component.component.html in the root app html file src/app/app.component.html add a custom html tag with the component name as follows,

<app-my-component></app-my-component>

Angular 4: Data Binding Two-Way-Binding

Initially the button is disabled until a username is input, after which time it is possible to reset the username by clicking the button.


In app.component.ts he simply declare two variables and set ‘username’ to an empty string. The function clears the string and resets the username.

export class AppComponent {
username: string = '';
allowButton: boolean = false;
onUsernameReset(){
this.username = '';
}
}

In app.component.html we use [(ngModel)] for two-way-databinding. This uses both square and round brackets. The input is set to ‘username’ and because of the two-way-binding this is available everywhere, e.g. for string interploation on the next line using {{ username }} and for property binding [disabled]=”!username”

<div class="container">
<div class="row">
<div class="col-md-4">
<label for="box">Username:</label>
<input name="box" type="text" class="form-control" [(ngModel)]="username"/>
<p> {{ username }} </p>
<button class="btn btn-primary" [disabled]="!username" (click)="onUsernameReset()">Reset username</button>
</div>
</div>
</div>

The ‘click’ event is put in round brackets and it calls the function onUsernameReset() which can be found in app.component.ts

Angular 4: Data Biding Event Binding

When an event occurs i.e. clicking a button we want a function onButton() to be called.

In app.component.ts we have the function onButton() which simply logs a few words to the console,

export class AppComponent {
onButton(){
console.log("You pressed it, well done!")
}
}

In app.component.html the event, in this case ‘click’, is in round brackets,

<button class="btn btn-primary">Button</button>

Angular 4: Basic Setup & Bootstrap

https://cli.angular.io/

Install Angular 4 using the Angular CLI tool,

$ npm install -g @angular/cli

Create a new app or project,

$ ng new my-new-app

This creates a new directory, next move in to it,

$ cd my-new-app

Run the app in development,

$ ng serve

Install bootstrap,

$ npm install --save bootstrap

Then add bootstrap to .angular-cli.json which can be found in the root of the project. Find the ‘styles’ and add the path for bootstrap like this,

"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],

It may be necessary here to run,

$ npm install

from the project root directory, the directory containing the node_modules directory.

You can then use bootstrap in my-new-app/src/app/app.component.html

<div class="container">
<div class="row">
<div class="col-md-4">one</div>
<div class="col-md-4">two</div>
<div class="col-md-4">three</div>
</div>
</div>

Angular Service Example

The following code demonstrates how a service can be created in AngularJS.

index.html

<html>
 <head>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js"></script>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-animate.min.js"></script>
 <script src="app.js"></script>
 <script src="anotherModule.js"></script>
 </head>
 <body>
 <div ng-app="mainModule" ng-controller="mainController as alias">
 <b>Invoice:</b>
 <p>The input is: {{alias.quantity}}</p>
 <div>
 Quantity: <input type="number" min="0" ng-model="alias.quantity"required>
 </div>
 <div><p>Add 4 and double it!</p></div>
 <div>
 <b>Result:</b>
 <span>{{alias.total(alias.quantity)}}</span>
 <button class="btn" ng-click="alias.paid(alias.total(alias.quantity))">Pay</button>
 </div>
 </div>
 </body>
</html>

app.js

angular.module('mainModule', ['dependencyModule'])
.controller('mainController', ['theService', function(theService) {

  this.quantity = 1;

  this.total = function total(number) {
    return theService.inService(number + 4);
  };

  this.paid = function pay(parameter) {
    window.alert(parameter);
  };

}]);

anotherModule.js

angular.module('dependencyModule', [])
  //currencyConverter is the service
.factory('theService', function() {

  var functionInService = function (parameter2) {
    return parameter2 * 2;
  };

  return {
    inService: functionInService
  };
});

Services can be used to share code across controllers.