Points to note, will be organized later
- To create a project component:
ng new angular-crash-course
- To create a new component:
ng generate component components/button
- To create a new service that is to be used by a component:
ng generate service services/task
- For loop in angular's xxx.component.html
<div *ngFor="let task of tasks"> {{ task.text }} </div>
- Pass object as a props:
<app-task *ngFor="let task of tasks" [task]="task"> </app-task>
-
import { Observable, of } from "rxjs";
- json server.
After
yarn add json-server
we add the following inpackage.json
as our script:"server": "json-server --watch db.json --port 5000"
import { HttpClient, HttpHeaders } from "@angular/common/http"
then
and add that intoimport { HttpClientModule } from "@angular/common/http";
app.module.ts
'simports
field. Next we can addHttpClient
in theTaskService
, then we can call the get method to getObservable
.- To call a function in a view model, we use
<div (click)="onClick()">
, whereonClick
is a method inxxx.component.ts
, the view model. - Suppose we have
then:import { Input, Output, EventEmitter } from "@angular/core";
@Input()
is used to define object as a props from parent to its child.@Output()
is used to define function that pass data from child to parent, which is usually anEventEmitter<T>
.- Suppose that we have defined
inside@Output() onDeleteTask: EventEmitter<Task> = new EventEimitter()
<app-task-item></app-task-item>
, then we can define
inside that item component.deleteTask(task) { this.onDeleteTask.emit(task)}
- In task-item (child) level, we can define
(click)=deleteTask(task)
, which will emit the event that ship with datatask
. - In tasks (parent) level, we can define
<app-tasks (onDeleteTask)=doSth(task)></app-tasks>
to subscribe for theEvent
.
- In task-item (child) level, we can define
- We add conditional class
reminder
based onshouldRemind: boolean
:
Once<div class="task" [ngClass]="{ reminder: shouldRemind }">...</div>
shouldRemind === true
, thediv
element will be of classtask reminder
, otherwise it is merely be of classtask
. - Apart from the usual
EventEmitter
:(click)
, we have(dblclick)
for double-click. - To enable two-way data binding (bind data between both view-model and UI), we:
Then we can use// src/app/app.module.ts import { BrowserModule } from "@angular/platform-browser"; ... @NgModule({ ... imports: [ BrowserModule, FormsModule ], ... })
ngModel
directive as follows:
where<input [(ngModel)]="text"/> <div> {{ text }} </div>
text
is an attribute defined inxxx.component.ts
. - To conditionally show an element, we use
*ngIf="classAttribute"
.