Wednesday 1 March 2017

Get selected values on click and show in the UI - Angular 2

There is lot of difference between angular one and two. Angular two is supporting JavaScript ES6 which is not yet supported by latest browsers however you can use current JavaScript ES5 with angular 2. But you may not be able to enjoy all features of angular 2 in this case. Let us check how we can show selected value on click in angular 2.

Component html


@Component({
  selector: 'my-app',
  template: `<div *ngIf="selected">
 <h4>Selected</h4>
 <p><strong>{{selected.name}}</strong></p>
</div>

<h2>{{title}}</h2>
<div>
 <ul>
  <li *ngFor="let i of items">
   <p (click)="showSelected(i)">{{i.name}} ({{i.exp}})</p>
   </li>
 </ul>
</div>
`
})

This part either you can add directly like above or move to a separate partial file and include in the component. For example like below code.


@Component({
  selector: 'my-app',
  template: `app/mayPartial.html`
})

Component logic


export class App {
    title: string;
    items: any[];
    selected:string;
    constructor() {
        this.title = "Angular 2 click";
        this.items = [{
            name:'Prashobh',
            exp:'9',
        },
        {
            name:'Abraham',
            exp:'15',
        },
        {
            name:'George',
            exp:'2',
        },
        {
            name:'John',
            exp:'20',
        }
        ]
    }
    showSelected(item){
        this.selected = item;
    }
}

Click on the names and see the result.

Related Post

1. ng-repeat in angular js 2

2. Angular 2 filter using pipe concept

3. ng-click in angular js 2

No comments :

Post a Comment