Angular 2 Components Example
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.
Example of Components
@Component({
selector: 'home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
})
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);
};
}
@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.
@Component({
selector: 'hello-world'
})
@View({
template: "<h1>Hello {{angular}}</h1>"
})
class hello {
constructor(public angular: string) {}
}
<hello-world></hello-world>
@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 Components and Directives has multiple life-time hooks where we custom logic
can be executed.
Angular 2 Constructors:-
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();
}
}
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.
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 {
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>
Example 2,
@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;
}
@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) {
}
}
<button (click)="addUser()">Click</button>
<button (click)="addUser($event)"></button>
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);
@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();
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>
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”.
Syntax:-
<div [hidden]="!active">
Hello, this is active area!
</div>
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;
}
@Injectable()
export class MyService {
constructor() { }
}
@Component({
selector: 'my-app',
templateUrl: './myApp.component.html'
})
export class MyAppComponent { }
@Component({
selector: '<my-component></my-component>',
templateUrl: 'app/component.html',
providers: [MyService]
})
@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();
}
}
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.
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>
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.
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.
@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;
});
}
}