You are on page 1of 3

Search

Angular CLI Template and Data Binding </button>


npm i -g @angular/cli <input [(ngModel)]="from" name="from"> </div>
 <!-- two way binding --> <table *ngIf="f.length > 0"> <!-- condition -->
ng new my-project <input [(ngModel)]="to" name="to"> <tr *ngFor="let f of flights"> <!-- iteration -->
cd my-project <td>{{f.id}}</td> <!-- interpolation -->
ng serve -o <div [hidden]="!to || !from"> <td>{{f.from}}</td>
 <!-- property binding (one way) --> <td>{{f.to }}</td>
ng generate component MyComponent <button (click)="search()"> <td>{{f.date | date:'dd.MM.yyyy HH:mm'}}</td>
ng generate service MyService  <!-- event binding -->  <!-- pipe -->
ng generate pipe MyPipe <td [class.active]="f === selectedFlight">
 <!-- condt. fmt. -->
ng build --prod <a (click)="select(f)">Select</a>
</td>
</tr>
</table>

Component
@Component({
selector: 'flight-search',
Consuming Service

Angular Cheat Sheet


templateUrl: './flight-search.component.html'
})
export class FlightSearchComponent { Service @Component({ […] })
export class FlightSearchComponent {
from: string; @Injectable({ providedIn: 'root' })

Concept & Content by Manfred Steyer


[…]
to: string;  // service registration constructor(private flightService: FlightService) { }
flights: Array<Flight> = []; export class FlightService {  // injection
selectedFlight: Flight; […]
constructor(private http: HttpClient) { }
search(): void { […] }  // constructor injection search(): void {
find(from: string, to: string): Observable<Flight[]> { this
select(f: Flight): void {
let url = 'http://www.angular.at/api/flight'; .flightService
this.selectedFlight = f;
let params = { from, to }; .find(this.from, this.to)
}
let headers = { accept: 'application/json'}; .subscribe( // subscribing to observable
}
return this.http.get<Flight[]>( flights => { this.flights = flights; },
 url, { params, headers }); err => { console.error('err', err); }
} );
} }
}
Custom Pipe Calling components with Importing the RouterModule
inputs and outputs with the configuration
@Pipe({
name: 'city', // name to use in template <flight-card @NgModule({
pure: true [item]="f" imports: [
}) [selected]="basket[f.id]" BrowserModule,
export class CityPipe implements PipeTransform { (selectedChange)="basket[f.id] = $event"> FormsModule,
transform(value: string, fmt: string): string { </flight-card> HttpClientModule,
// FlightBookingModule,
[…]
<!-- if event is called like property + Change, // don’t import lazy modules!
return formattedCity;
e. g. selected and selectedChange, and RouterModule.forRoot(APP_ROUTES)
} event publishes new value for property,  // reference routing config
} we can use syntax for two way binding -->  // use forChild for feature modules!
],
<flight-card declarations: [
[item]="f" […]
Inputs and outputs [(selected)]="basket[f.id]"> // don’t forget to register your components
</flight-card> ],
@Component({ bootstrap: [AppComponent]
selector: 'flight-card', })
templateUrl: './flight-card.component.html' export class AppModule { }

Angular Cheat Sheet


}) Routing Configuration
Lifecycle Hooks
export class FlightCardComponent { export const APP_ROUTES: Routes = [
@Input() item: Flight; {

Concept & Content by Manfred Steyer


@Input() selected: boolean; path: '',
@Output() selectedChange = redirectTo: 'home', Markup for routing
 new EventEmitter<boolean>(); pathMatch: 'full'
}, <a routerLink="home"></a>
select() { <a routerLink="flight-booking/flight-search">
this.selected = true; {
this.selectedChange.next(this.selected); path: 'home',
component: HomeComponent}, […]
// trigger event when needed
{path: 'flight-booking', <router-outlet></router-outlet>
}
deselect() { loadChildren: () => // lazy loading
this.selected = false; import('./flight-booking/flight-booking.module')
this.selectedChange.next(this.selected); .then(m => m.FlightBookingModule)},
} {path: '**',
} redirectTo: 'home'}
];
Routing config with Reading routing parameter Lifecycle Hooks
parameter @Component({ @NgModule({
export const FLIGHT_BOOKING_ROUTES: Routes = [ selector: 'app-flight-edit', imports: [
[…] templateUrl: './flight-edit.component.html',}) CommonModule,
{ export class FlightEditComponent implements OnInit { FormsModule,
path: 'flight-edit/:id', id: string; SharedModule,
 // just for parameters in url segments showDetails: string; […]],
 // you don’t need to register other url params declarations: [
component: FlightEditComponent constructor(private route: ActivatedRoute) { }
// ActivatedRoute represents the current route FlightSearchComponent,
} FlightCardComponent,
// including parameter
]; PassengerSearchComponent,
ngOnInit() {
this.route.params.subscribe(p => { FlightEditComponent],
this.id = p['id']; providers: [
 // from url segment as configured // Providers are global!
this.showDetails = p['showDetails']; // Traditional way for registering a service
Link with routing parameter  // url parameter
// Alternative to { providedIn: 'root' }
}); { provide: FlightService, useClass: FlightService }
<a [routerLink]= // Alternative, when provide
}
"['/flight-booking/flight-edit', item.id, // and useClass points to same type:
}
// FlightService

Angular Cheat Sheet


{showDetails: true}]">Edit</a>
],
exports: [
// Exports can be used in other modules
// which are importing this module

Concept & Content by Manfred Steyer


ngOnChanges(changes: SimpleChanges): void { FlightSearchComponent]
Lifecycle Hooks if (changes['item']) { })
// item changed export class FlightBookingModule {
@Component({ }
}
selector: 'flight-card',
}
templateUrl: './flight-card.component.html'
}) ngOnDestroy(): void {
export class FlightCardComponent […] Manfred Steyer is a Trainer and Consultant with a
implements OnInit, OnChanges, OnDestroy { } focus on Angular. He is a Google Developer Expert
(GDE) who writes for O’Reilly, Java Magazin, win-
ngOnInit() { […] dows.developer, and Heise. He regularly speaks at
conferences.
[…] }
} Web: www.softwarearchitekt.at

You might also like