Shalvin Interests

Sunday, January 29, 2017

Angular 2 Contact Management Part 2 :Binding to Array of Class


app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';

import { AppComponent }  from './app.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }




On to the existing app.module.ts import FormModule which is essential for implementing two way data binding.

app.component.ts

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

export class Contact {
  id: number;
  name: string;
  specialization:string;
}

const CONTACTS: Contact[] = [
  { id: 11, name: 'Shalvin', specialization : '.Net' },
  { id: 12, name: 'Praveen', specialization : 'Big Data' },
  { id: 13, name: 'Anuraj', specialization : 'Asp .Net Core' },
  { id: 14, name: 'Praseed', specialization :'C++' },
  { id: 14, name: 'Yaneesh', specialization :'.Net' }
];

@Component({
  selector: 'my-app',
  template: `
    <h1>{{title}}</h1>
    <h2>My Contacts</h2>
    <ul>
      <li  *ngFor="let Contact of Contacts"
         (click)="onSelect(Contact)">
         {{Contact.name}}
      </li>
    </ul>
    <div *ngIf="selectedContact">
      <h2>{{selectedContact.name}} details!</h2>
      <div><label>id: </label>{{selectedContact.id}}</div>
      <div>
        <label>name: </label>
        <input [(ngModel)]="selectedContact.name" placeholder="name"/>
      </div>
       <div>
        <label>Specailization: </label>
        <input [(ngModel)]="selectedContact.specialization" placeholder="specialization"/>
      </div>
    </div>
  `
})
export class AppComponent {
  title = 'Contact Management';
  Contacts = CONTACTS;
  selectedContact: Contact;

  onSelect(Contact: Contact): void {
    this.selectedContact = Contact;
  }
}

 

 Clicking on a Contact it's details will be displayed below.

No comments:

Post a Comment