0% found this document useful (0 votes)
56 views

Angular 2 Components Example

- Angular 2 uses components as the fundamental way to build and organize the user interface and application logic. Components define views, styles, and logic for a specific section of the UI. - Components are defined using metadata annotations and can import templates, stylesheets, and logic. The root AppComponent contains all other components in a tree structure. - Data can be passed into components using the @Input decorator and events can be emitted from components using the @Output decorator, allowing communication between parent and child components.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views

Angular 2 Components Example

- Angular 2 uses components as the fundamental way to build and organize the user interface and application logic. Components define views, styles, and logic for a specific section of the UI. - Components are defined using metadata annotations and can import templates, stylesheets, and logic. The root AppComponent contains all other components in a tree structure. - Data can be passed into components using the @Input decorator and events can be emitted from components using the @Output decorator, allowing communication between parent and child components.

Uploaded by

Ashihs
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Angular 2 Components Example

In Angular 2, the components are the main way to build or specify HTML elements and business
logic on the page.

In AngularJs 1, we are handling using scope, directives and controllers but all those concepts
are using in a single combined that is called components.

The component is the core functionality of Angular 2 app but we need to know to pass the data
in to the components to configure them.
To build an Angular 2 application you define a set of components, for every HTML elements,
views, and route.

Angular 2 applications must have a root component that contains all other components. That
means all Angular 2 applications have a component tree.

Application  Component  Component1 and Component2

Example of Components

import { Component } from '@angular/core';


import { CommonModule } from '@angular/common';

@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})

export class HomeComponent {


userlist: Users[];

constructor() {
this.userlist = [
{ Id: '1001', name: 'Anil Singh', site: 'http://www.code-sample.com' },
{ Id: '1002', name: 'Alok', site: 'http://www.code-view.com' },
{ Id: '1003', name: 'Reena', site: 'http://www.code-sample.xyz' },
{ Id: '1004', name: 'Dilip', site: 'http://www.codefari.com' },
];
}

values = '';
onKeyUp(event: any) {
this.values = event.target.value;
console.log(this.values);
};

onKeyDown(event: any) {
this.values = event.target.value;
console.log(this.values);
};
}

export class Users {


Id: String;
name: String;
site: String;
}

/* For HTML Components


<input type="text" [(value)]="values" (keyup)="onKeyUp($event)" (keydown)="onKeydown($event)" />
*/

Angular 2 Component Summary

 Angular 2 Component meta-data annotation is used to register the components.


 Angular 2 components are used to create UI widgets.
 Angular 2 components are used to split to application into smaller parts.
 Only one component is used per DOM element.
 In the Angular 2 components, @View, template and templateUrl are mandatory in the
components.

Angular 2 components vs directives


Angular 2 components vs directives

@Components @Directive
1. @Component meta-data annotation is @Directive meta-data annotation is
used to register the components. used to register the directives.
2. The components are used to create UI The directives are used to add behavior to
widgets. existing DOM elements.

3. The components are used to split to The directives are use to design a reusable
application into smaller parts. components.
4. Only one component is used per DOM More than one directive are used per
element. DOM element.
5. In the components, @View, template and The directive do not have @View etc.
templateUrl are mandatory in the
components.

Example for using Component.


import {Component, View} from 'angular2/core';

@Component({
selector: 'hello-world'
})

@View({
template: "<h1>Hello {{angular}}</h1>"
})

class hello {
constructor(public angular: string) {}
}

<hello-world></hello-world>

Example for using Directive.


import {Component, View} from 'angular2/core'';

@Component({
selector: 'user-detail'
})

@View({
template: "<div> <h1>{{userName}}</h1> <p>{{phone}}</p>"
})
class userDetail {
constructor(public userName: string, public phone: string) {}
}

<user-detail></user-detail>

Angular 2  Component Lifecycle Hooks [Examples Also]


The common questions ask bye most of Angular 2 lovers,

“Could anyone tell me about the usage of ngOnInit if we already have a


constructor?” but Angular 2 provides life cycle hook ngOnInit by default.

Angular 2 Components and Directives has multiple life-time hooks where we custom logic
can be executed.

Angular 2 Constructors:-

The constructor is a default method runs when component is being constructed.


The constructor is a typescript feature and it is used only for a class instantiations and
nothing to do with Angular 2.

The constructor called first time before the ngOnInit().

Example as,
import {Component} from 'angular2/core';
import {UserService} from './userService';

@Component({
selector: ‘list-user’,
template: `<ul><li *ngFor="#user of users">{{user.name}}</li></ul>`
})

class App_Component {
users:Array<any>;
constructor(private _userService: UserService) {
this.users = _userService.getUsers();
}
}

Angular 2 ngOnInit and ngOnChanges:-

The ngOnInit event is an Angular 2 life-cycle event method that is called after the first
ngOnChanges and the ngOnInit method is use to parameters defined with @Input
otherwise the constructor is OK.

The ngOnInit is called after the constructor and ngOnInit is called after the first
ngOnChanges.

The ngOnChanges is called when an input or output binding value changes.

Examples as,
import {Component, OnInit} from '@angular/core';
export class App implements OnInit{
constructor(){
}

ngOnInit(){
}
}
Angular 2 ngOnDestroy :-

The ngDestroy directive is called in a component lifecycle just before the instance of the
component is finally destroyed.

Example as,
@Directive({
selector: '[destroyDirective]'
})
export class OnDestroyDirective implements OnDestroy {

//Call Constructor and set hello Msg.


constructor() {
this.helloMsg = window.setInterval(() => alert('Hello, I am Anil'), 2000);
}

//Destroy to the component


ngOnDestroy() {
window.clearInterval(this.helloMsg);
}
}

Angular 2 Complete lifecycle hook interface inventory:-

1. ngOnChanges - called when an input binding value changes.


2. ngOnInit - after the first ngOnChanges.
3. ngDoCheck - after every run of change detection.
4. ngAfterContentInit - after component content initialized.
5. ngAfterContentChecked - after every check of component content.
6. ngAfterViewInit - after component's view(s) are initialized.
7. ngAfterViewChecked - after every check of a component's view(s).
8. ngOnDestroy - just before the component is destroyed.

Angular 2 Lifecycle Events Log:-


1. onChanges
2. onInit
3. doCheck
4. afterContentInit
5. afterContentChecked
6. afterViewInit
7. afterViewChecked
8. doCheck
9. afterContentChecked
10. afterViewChecked
11. onChanges
12. doCheck
13. afterContentChecked
14. afterViewChecked
15. onDestroy

Angular 2 @Inputs - How to Passing data into Angular 2


components with @Input?
@Input allows you to pass data into your controller and templates through html
and defining custom properties.

@Input is used to define an input for a component, we use the @Input


decorator.

Angular 2 components is the core components of applications but you must


need to know “how to pass data into components to dynamically?” and that time
you need to define an input component.

Stayed Informed - Angular 2 @Output


You can see the below example for passing the user data in to the components.

Example 1,
import { Component, Input } from '@angular/core';

@Component({
selector: “user-info”,
template: “<div> Hello, This is {{ userInfo.name}}</div>”
})
export class UserInfo {
@Input() userInfo;
constructor() { }
}

<user-info [userInfo]="currentUser"></user-info>

The components <user-info></user-info> is use to render the user information on


the view.

Example 2,

import { Component } from '@angular/core';

@Component({
selector: 'app-root',
styles: [`
.app {
text-align: center;
background: #f5f5f5;
}
`],
template: `
<div class="app">
<counter [count]="defaultCount"></counter>
</div>
`
})
export class AppComponent {
defaultCount: number = 20;
}

Angular 2 Component Outputs [@Output Property]


@Output decorator is used to binds a property of a component to send the data
from child component to parent component and this is a one-way
communication.

@Output decorates output properties and its binds a property of the type of
angular EventEmitter.
If you want to bind an event on an element, you can use the
new Angular2 events i.e.

@Component(...)
class yourComponent {
addUser(event) {
}
}

The method addUser() will be called when user clicked on button.

<button (click)="addUser()">Click</button>

<button (click)="addUser($event)"></button>

What happen if you want to create a custom event?

Now come to the outputs, if you want to create your custom event in Angular
2 that time we will use to new @Outputdecorator.

Examples,
import { Component} from 'angular2/core';
import { bootstrap} from 'angular2/platform/browser';

@Component({
selector: 'my-app',
providers: [Service],
template: '<div>Hello my name is {{name}}!</div>'
})
class MyApp {
constructor(service: Service) {
this.name = service.getName();
setTimeout(() => this.name = 'Anil Singh,', 1000);
}
}
class Service {
getName() {
return 'Hello';
}
}

bootstrap(App);

In the above example, we will need to import Output and Event-Emitter to


create our new custom event.

import { Component , Output, EventEmitter} from 'angular2/core';


import { bootstrap} from 'angular2/platform/browser';

@Component({
selector: 'my-app',
providers: [Service],
template: '<div>Hello my name is {{name}}!</div>'
})
class MyApp {
constructor(service: Service) {
this.userClicked.emit(this.user);

this.name = service.getName();

setTimeout(() => this.name = 'Anil Singh,', 1000);


}
}
class Service {
getName() {
return 'Hello';
}
@Output() userClicked = new EventEmitter();
}
bootstrap(App);

Now when we are using the components anywhere in our application, we can
bind the custom event i.e.

<my-app (userClicked)="userClicked($event)"></my-app>

Angular 2 Hidden Attribute with Multiple Examples


Angular 2 [hidden] is a special case binding to hidden property.

It is closest cousin of ng-show and ng-hide.

It is more powerful to bind any property of elements. Both the ng-show and ng-
hide are used to manage the visibility of elements using ng-hide css class. It is
also set the display property “display:none”.

Stayed Informed - Angular 2 @Inputs


All the above features are supported in Angular 2 but added some extra feature
like animations etc.

Syntax:-
<div [hidden]="!active">
Hello, this is active area!
</div>

Note: - Don't use hidden attribute with Angular 2 to show/hide elements.

Question: - Don't use hidden attribute with Angular 2. Here is why?


The hidden attribute is used to hide elements. Browsers are not supposed to
display elements that have the hidden attribute specified. Browsers attach
"display: none" styles to elements with hidden attribute.

Example,
import { Component } from 'angular2/core';

@Component({
selector: 'demo',
templateUrl: 'app/component.html'
})
export class MainComponent {
Ishide: true;
}

<div [hidden]="Ishide">
Hey, I’m using hidden attribute.
</div>

Works great but some time its override hidden attribute with some css and that
time behave wrong!..

For example,
Be sure to don't have a display css rule on your <p> tags who override hidden
behaviour like i.e.

p{
display: inline-block !important;
}

The above hidden html attributes acts like display: none;

How do Components Communicate with Each Other in Angular


2?
In Angular 1, I have some ways to communicate between controllers i.e.
1. $rootScope,
2. $scope,
3. $emit,
4. $broadcast

Now In Angular 2, we have different ways to communicate between components.


A parent component and its children share a service whose interface enables bi-directional
communication within the family.

Stayed Informed - Angular2 Components Life-cycle

The following examples for Services communication,


import {Injectable} from '@angular/core';

@Injectable()
export class MyService {
constructor() { }
}

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
templateUrl: './myApp.component.html'
})
export class MyAppComponent { }

The following example to calling service from any other component,


import {Component, OnInit} from '@angular/core';
import {MyService} from './app/myService';

@Component({
selector: '<my-component></my-component>',
templateUrl: 'app/component.html',
providers: [MyService]
})

export class MyComponent implements OnInit {


constructor(private msInstance: MyService) {}
ngOnInit() {
this.msInstance.getServices();
}
}

Example for Sibling Component Communication,

import { Component, ViewChild, AfterViewInit } from '@angular/core';


import { ListComponent } from './list.component';
import { DetailComponent } from './detail.component';

@Component({
selector: 'app-component',
template: '<list-component></list-component><detail-component></detail-component>',
directives: [ListComponent, DetailComponent]
})
class AppComponent implements AfterViewInit {
@ViewChild(ListComponent) listComponent:ListComponent;
@ViewChild(DetailComponent) detailComponent: DetailComponent;

ngAfterViewInit() {
// afther this point the children are set, so you can use them
this.detailComponent.doSomething();
}
}

For live Result https://embed.plnkr.co/h25J1Mv6ioUWVX5g6t5M/

How do we display errors in a component view with Angular 2?


In Angular 1, the ng-messages modules are used to help us to display error messages and
validation to our forms.

In Angular 2, the ngModel provides error objects for each of the built-in input validators. You can
access these errors from a reference to the ngModel itself then build useful messaging around
them to display to your users.

Stayed Informed - Angular2 email forms validation

And also, we can use the properties “pristine” and “touched” to display error messages.

1. If we want to display errors after the user fills something in a field, use the pristine property.
2. If we want to display errors after the user put the focus on a field, use the touched property.

Example as,
<div *ngIf="(!loginForm.controls.email.valid && !loginForm.controls.email.pristine)">
**Email is required.
</div>

For example 2 click..

ElementRef vs Renderer - Angular 2


What are the difference between Renderer and ElementRef in angular 2?

ElementRef vs. Renderer -


In Angular Renderer and ElementRef are used for DOM Manipulation and Renderer and
ElementRef are used together to get full platform abstraction.
Renderer –
Renderer is a class that is a partial abstraction done the DOM manipulations and the DOM
manipulating is not breaking server side rendering or web workers.

ElementRef –
ElementRef is a class that is a partial abstraction done the DOM Manipulations without
breakable environments and it also can hold a reference to a DOM elements.

If “ElementRef” is injected to a component, the injected instance is a reference to the host


element of the current component.

The ways to get an ElementRef instance looks like,


1. @ViewChild()
2. @ViewChildren()
3. @ContentChild()
4. @ContentChildren()

In this case the ElementRef is a reference to the matching elements in the templates.

Do notice that you should refrain from using ElementHref as it flagged with a security risk?
If you allow direct access to the DOM, it can make your application more vulnerable to XSS
attacks. So make sure, when you are using to ElementRef in your app code.

What is the point of calling renderer.invokeElementMethod(rendererEl, methodName)?

//our root app component


import {Component, ElementRef} from 'angular2/core'
import * as browser from 'angular2/platform/browser'
import {Ruler, Rectangle} from 'angular2/src/platform/browser/ruler.js'

@Component({
selector: 'my-app',
providers: [ElementRef],
template: `
<div>
<h2>Hello {{name}}</h2>
<p>H2 Height: {{rect.height}}</p>
<p>H2 Width: {{rect.width}}</p>
</div>
`,
directives: []
})
export class App {
constructor(element: ElementRef) {
this.name = 'Angular2'
this.element = element;
this.ruler = new Ruler(new browser.BrowserDomAdapter());
this.rect = {};
}
ngOnInit() {
var vm = this;
var measure = this.ruler.measure(this.element);
measure.then(function (rect) {
console.log('Rect', rect);
vm.rect = rect;
});
}
}

You might also like