Angular Cheat sheet
Defines the full guide of Angular to start the new application
Create Angular 13 Application:
- Install nodejs@13.0.0 & it will install npm@8.1.2
node -v
npm -v
npm install -g @angular/cli@13.0.0
ng version
App Configuration:
Angular CLI: 13.0.0
Node: 16.13.1
Package Manager: npm 8.1.2
OS: win32 x64
Forms:
- Template-driven Form — Basic form
- Rely on directives in the template to create and manipulate the model. Simple form to an app , such as sing up form. If you have very basic requirements and logic then template driven forms could be a good fit
- Reactive Form — Advanced
Reactive Form :
- Declare ReactiveModule in Module.ts
import { ReactiveFormsModule } from '@angular/forms'
- Add FormGroup and Formcontrolname in Template
<form [formGroup]="loginForm " name="login">
<input type="text" formControlName="username" placeholder="Name" />
</form>
- Declare formGroup and FormControl in Component
loginForm = new FormGroup({
email: new FormControl(""),
password: new FormControl("")
})
- Get Form Value in Component
this.loginForm.get('email')?.value
Reactive Form Validation:
- Add form validation in Template
<input type="email" formControlName="email" placeholder="Email" required />
- Add Validators in component
loginForm = new FormGroup({
email: new FormControl("",Validators.required),
password: new FormControl("", Validators.required)
})
New Application Components/Folder structure
Dynamic class in DOM Element
Element Ref is from angular core module which will give the DOM element.
main!: ElementRef;
this.main.nativeElement.setAttribute('class', 'container right-panel-active');
Behavior Subject
It is a special type of observable in Rxjs that keeps track of current value and emits it to subscribers.
It is similar to subject but it also emits the latest value to be passed to it.
This is useful when u want to use default value or latest value
private myBehaviorSubject = new BehaviorSubject<User>(User);
setValue(User: User) { this.myBehaviorSubject.next(user); }
getValue() { return this.myBehaviorSubject.asObservable(); }
this.currentUser$ = getValue();
this.userService.currentUser$.subscribe(user => {
this.currentUser = user;
})
Cookie Storage
Client side storage ,
Cookies are limited in size, typically to 4 KB of data
npm i @ngx-cookie-service
constructor(sprivate cookieService: CookieService)
this.cookieService.set('USER_INFO', JSON.stringify(userModel.data));
const userCookie = this.cookieService.get('USER_INFO');
Local Storage
Client side storage ,
storage of more data, up to 5 MB
localStorage.setItem('loggedInUser', user);
localStorage.getItem('loggedInUser');
Interceptor — Auth & Error
Interceptor is used to add the Token in the header. Authorization on each request using the token in the header.
@Injectable()
export class JwtInterceptor implements HttpInterceptor {
constructor(private userService: UserService) { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let token: any = '';
let loggedInUser: any = '';
this.userService.currentUser$.subscribe(user => {
if(!!user && user.userName){
token = user.jwtToken;
loggedInUser = user?.userName;
}
})
if (loggedInUser !== '' && token !== '') {
request = request.clone({
setHeaders: { Authorization: `Bearer ${token}` }
})
}
return next.handle(request);
}
Need to add it in the providers in app module
providers: [
UserService,
CookieService,
{ provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }
],
Observable
const observable = rxjs.Observable.create(observer => { console.log('Text inside an observable');
observer.next('Hello world!');
observer.complete(); });
console.log('Before subscribing an Observable');
observable.subscribe((message)=> console.log(message));
Promise
const promise = new Promise((resolve, reject) => { console.log('Text inside promise');
resolve('Hello world!'); });
console.log('Before calling then method on Promise');
greetingPoster.then(message => console.log(message));
Angular Key points:
- Misko Hevery is the father of AngularJS.
- ng-model is used to find the values of HTML controls to application data
- $https Services used to make an Ajax call to the server.
- RxJS can be used for both Server-side and browser.
- main.ts is Responsible for the startup of the angular project
- zone.js is used to detect changes in the angular project.
- routerOutlet is a directive defined in the HTML indicating where the route’s view should display.
- @input is used to share data from the parent component to the child.
- @output is used to share data from child component to parent.
- forChild() is used to import RouterModule in a feature module.
- Most used CSS frameworks are bootstrap.
- Transpiler are the source to source compiler.