Creating and Communicating Between Components
Check code at: https://github.com/wghglory/angular2-fundamental
Creating Our First Data-bound Component
1) create events/events-list.component.ts:
1 | import { Component } from '@angular/core' |
2) modify app.component.ts:
1 | import { Component } from '@angular/core' |
3) update module:
1 | import { NgModule } from '@angular/core' |
Using External Templates
1) create events-list.component.html as template:
1 | <div> |
2) modify events-list.component.ts using templateUrl instead of template:
1 | import { Component } from '@angular/core' |
Components Interaction
1. Communicating with Child Components Using @Input (Parent pass data to child)
I want to create a address component as a child component. The parent component, events-list, will pass the event object to the child. To get this done:
- child component needs import Input from angular/core
- parent template uses the child selector, and [child object name] = “parent”
1) create child component events-address.component.ts
1 | //child component, talk with parent events-list.component.ts |
2) modify parent component template, [address] is child object name, “event.location” is parent data
1 | <div> |
3) import child component to app.module
1 | import { EventsAddressComponent } from './events/events-address.component' |
2. Communicating with Parent Components Using @Output and EventEmitter (child pass data to parent)
1) child component “events-address.component.ts”:
- import Output, EventEmitter
- define a variable accepting EventEmitter
- define buttonClick
- the EventEmitter variable emit any data from child component
1 | //child component, talk with parent events-list.component.ts |
2) parent Component “events-list.component.ts”:
update template: (the EventEmitter variable name defined in child component) = “randomFuncInParent($event)”
1
<events-address (myclick)="clickWithAnyName($event)"></events-address>
define random function in parent component class
1
2
3
4
5export class EventsListComponent {
clickWithAnyName(dataFromChild){
alert(dataFromChild)
}
}
3. Using Template Variables To Interact with Child Components (parent access to child data, easier than method 2)
1) child component events-address.component.ts define public property and method
1 | //child component, talk with parent events-list.component.ts |
2) access child component data from parent component template’s childPointer variable
1 | <events-address [address]="event.location" (myclick)="clickWithAnyName($event)" #childPointer></events-address> |
Styling Components
By default, style scope is current component: the class defined below works only in current component, any other component applied same class won’t work.
Global css can be placed in styles.css
1 | @Component({ |
Create Navbar
create nav/nav.component.ts and its template nav.component.html, then export component into module.
1 | import {Component} from '@angular/core' |