0% found this document useful (0 votes)
48 views32 pages

Angular Cheat

Angular cheat

Uploaded by

Laszlo Kamler
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
48 views32 pages

Angular Cheat

Angular cheat

Uploaded by

Laszlo Kamler
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
nv oll >[Link] Cheat w\9 Silay : Before we get started, let's touch briefly upon Angular JS. The background will help you understand the greater purpose behind using the Angular framework in your work, What is Angular JS? Google developed AngularJS, a Javascript framework that helps developers to create fully scaled single-page web apps. The term "single page" refers to the necessity for web pages to be updated A single web page consists of multiple moving parts and their organization— navigation bar, footer, sidebar, and more. To inject these components into the same web page, we use AngularJs, Bottom line? AngularJS makes the web page dynamic. Instead of refreshing the page when a user navigates to a URL, AngularJS injects the needed components into the same page. It basically reuses the components that don't change, which cuts down on load time and offers a better browsing experience. Now, let's get into some Angular commands. Angular CLI Cheat Sheet The Angular command-line interface (CLI) is a set of commands that help you initialize, develop, and maintain highly scalable and speedy Angular apps directly from the command shell. In this Angular CL! commands cheat sheet section, we'll cover various Angular Cl commands. 4. Setup ‘The following command installs Angular CLI globally: npm install -g @angular/cli 2. New Application The following command sets the prefix to “best.” practises --prefix best This command checks the available command list. ng new --help This command simulates the “ng new” command: ng new best-practises --dry-run 3. Lint for Format 9 The Lint command fixes code smells and corrects improper formatting. ng lint my-app --fix This next command shows warnings: ng lint my-app Hf you want to format the code, you can use the following command. ng lint my-app --format stylish Next, this command verifies the accessible list of commands. lint my-app --help 4, Blueprints Generate spec --spec Check whether the template will be a-ts file or not: inline-template Check whether the style will be in the-ts file or not --inline-style (-s) Create a directive: ng g d directive-name Create a pipeline: ng g p init-caps Create customer class in the models folder: ng g cl models/customer Creates a component without the need for the creation of a new folder. ng g ¢ my-component --flat true Assign a prefix: --prefix Create an interface in the models folder: ng g i models/person Create an ENUM gender in the models folder: ng g € models/gender Create a service’ 5. Building Serving Build an app to /dist folder: ng build Optimize and build an app without using unnecessary code: ng build --aot Create a build for production: ng build --prod Specify serve with opening a browser: ng serve -o Reload when changes occur: ng serve --live-reload Serve using SSL ng serve -ssl 6. Add New Capabilities ‘Add angular material to project: ng add @angular/material Create a material navigation component: ng g @angular/material:material-nav --name nav Components and Templates Components are the most fundamental Angular UI building pieces. component tree makes up an Angular app. Sample Component ts File import { Compon } from '@angular/core'; @Component ({ // component a’ selector: template’ styleUrls: » export class AppCompon: title = 'Hello World'; Component Attributes changeDetection The change-detection strategy to use for this component. viewProviders Defines the set of injectable objects visible to its view DOM children. moduleld The module ID of the module that contains the component. An Angular encapsulation ‘An encapsulation policy for the template and CSS styles, interpolation Overrides the default encapsulation start and end delimiters ({{ and }} entryComponents Asset of components that should be compiled along with this component. preserveWhitespaces True to preserve or false to remove potentially superfiuous whitespace characters from the compiled template Component Life Cycles ngOntnit Called once, after the first ngOnChanges() ngOnChanges Called before ngOnInit() and whenever one of the input properties changes. ngOnDestroy Called just before Angular destroys the directive/component. ngDoCheck Called during every change detection run. ngAfterContentChecked Called after the ngAfterContentinit() and every subsequent ngDoCheck() ngAfterViewChecked Called after the ngAfterViewlnit() and every subsequent ngAfterContentChecked() ngAfterContentinit Called once after the first ngDoCheck() ngAfterViewInit Called once after the first ngAfterContentChecked() Template Syntax {{[Link]}} Interpolation - generates user name. property binding - bind image url for user to sre attribute Event - assign function to click event ser. sho Angular ngClass attribute
Angular ngStyle attribute Input and Output Input() To pass value into child component Sample child component implementation: export class SampleCompon: @Input () value: any/s { ‘ing/obje ‘Sample parent component usage: (some html here)
Child component template: Let us now inject the following HTML code in the parent component template:
(some html here)
It will look like:
(some html here)
(some html here)
When we combine both the above parent and child template, you get the following result:
(some html here)
(some html here)
ViewChild Decorator Offers access to child component/directive/element: @ViewChild (NumberComponent. private numberComponent: NumberComponent; increase() { [Link](); — //method component, } decrease () { this. numberComponent .decreaseByOne (); //method component, } from from child child Sample for element: html:
component: @ViewChild('myElement') myBlement: ElementRef Instead ElementRef can be used for specific elements like FormControl for forms. Reference to element in html: active">Cri routerLinkActive active active" will add active class to element when the link's route becomes //Navigate from code x this. ro navigate (['/heroes']); // with parameters [Link](['/heroes', { id: heroId, foo Me // Receive parameters without Observable let id e. snapshot .paramMap.g CanActivate and CanDeactivate In Angular routing, two route guards are CanActivate and CanDeactivate. The former decides whether the route can be activated by the current user, while the latter decides whether the router can be deactivated by the current user. CanActivate: class UserToken {} UserToken, id: ring): boolean { CanDeactivate: class UserToken {} class Permissions { canDe; ivate(user: UserToken, id: string): boolean { return true; Modules Angular apps are modular and Angular has its own modularity system called NgModules. NgModules are containers for a cohesive block of code dedicated to an application domain, a workflow, or a closely related set of capabilities. Sample Module with Comments import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppRoutingModule } from './[Link]'; import { AppComponent } from './[Link]: @NgModule ({ declarations: | [AppComponent], // components, _— pipes directives imports: [BrowserModule, AppRoutingModule], // other modules providers: [], // services bootstrap: [AppComponent] // top component » export class AppModule { } Services Components shouldn't fetch or save data directly and they certainly shouldn't knowingly present fake data. Instead, they should focus on presenting data and delegate data access to a service, Sample service with one function: @Injectable() export class MyService { public items: Item[]; constructor() { } // some implementation When you create any new instance of the component class, Angular determines the services and other dependencies required by that component by looking at the parameters defines in the constructor as follows: constructor (private doghistService: MyService){ } The above constructor requires the service: wyService Register MyService inthe providers module: providers: [MyService] HttpClient This command handles and consumes http requests. Add import to module: import { ClientModule} from "@angular/common/ You can use the above statement in the following way: import {HttpClient} from '@angular/common/' // GET public getData(): Observable { return this. [Link] (‘api/users/2"); // Post public send(vall: any, val2: any): Observable const object = new SendModel(vall, val2); const options {headers: new HttpHeaders({'Content-type ‘application/json'})}; return [Link]([Link] + ‘api/login', object, options); Dependency Injection This injects a class into another class: @Injectable({ providedIn: 'root', » export class SomeService {} It accepts ‘root! as a value or any module of your application. Declare Global Values Class: import {InjectionToken} from '@angular/core! export const CONTR OLS_GLOBAL_CONFIG = new InjectionToken('global-values") ; export interface ControlsConfig (firstGlobalvalue ‘ing; } Module: providers: [{provide: CONTROLS_GLOBAL_c useValue: {firstGlobalValue : ‘Some value’ }}, Usage (for example in component): con or (@Optional () @Inject (CONTROL: globalVlues: ControlsConfig) { | GLOBAL_CONFIG) Pipes Pipes transform data and values to a specific format. For example: Show date in shortDate format {{[Link] | date:'shortDate'}} Pipe implementation: @Pipe({name: 'uselessPipe'}) export class uselessPipe implements PipeTransform { transform(value: fter: string): string { = “${before} ${value} ${after}*; usage: {{ [Link] | uselessPipe:"Mr. Directives An Attribute directive changes A DOM element's appearance or behavior. For example, [ngStyle] is a directive. Custom directive: import { Directive, ElementRef, HostListener, In| from "@angular/core'; @Directive ({ selector: '[appHighlight]' export class HighlightDirective { constructor (private el: BlementRef) { } @Input (‘appHighlight') high color: string; @Input (totherPar') otherPar: any; //it will be taken from ribute named [other?ar] stener('mouseenter') onMouseEnter() { [Link] cColor || 'red"); this. highlig private highlight (color: string) { [Link] Usage:

Highlignt me!

Animations Animations allow you to move from one style state to another before adding BrowserModule and BrowserAnimationsModule to the module. Implementation: e(‘closed', style({ height: '100px', opaci: ), transition(‘open => closed", [ animate ("1s") D, ransition('closed => open', [ animate ("1s") ) yD Usage Angular Forms In this section of our Angular 4 cheat sheet, we'll discuss different types of Angular forms. Template Driven Forms Form logic (validation, properties) are kept in the template, sample html
First Name is required
Register Sample component: QViewChila("£") form: any; firstName: string langs: string[] = ["English", "French", "German"]; onSubmit() { if (this. [Link]) { [Link]("Form Submitted!" this. form. reset ()7 Reactive Forms Form logic (validation, properties) are kept in the component. Sample HTML:
"onSubmit ()"
Email is required
Bmail must be a valid email address
Register
Sample component: registerForm: FormGroup; submitted = false; constructor (private formBuilder: FormBuilder) { ngonInit() { [Link] - this. [Link] ({ firstName: [i {here default value}}, validators. required], lastName: ['', Validators. required] email: ['', [[Link], [Link]]] password: a (Validators. required [Link](6)]] Ve // convenience getter for easy access to form fields get £() { return [Link]; } onSubmit() { [Link] = true; // stop here if form is invalid if ([Link]) { return; alert (SUCCESS! ! Custom Validator for Reactive Forms Function: validateUrl (control: AbstractControl) { if (![Link] || [Link]('.png') || [Link]('.jpg')) { return null; return { validUrl: true }; Usage: [Link] = this._formBuilder.group({ imageCtrl: ['', [[Link], [Link]]] Multi-field validation: validateNameShire (group: FormGroup) { if (group) { if ([Link]('isShirectrl').value —&& [Link] (*nameCtrl'). value. toString () .toLowerCase(). includes (' shire')) { return { nameShire : true }; return null; Multi-field validation usage:* this. firstFormGroup. setValidators (this. validateNameshire) ; Error handling
Name is too long
Sh dogs should have "shire" in name
Custom Val lator Directive for Template-Driven Forms Shortly, we'll cover how to register our custom validation directive to the NG_VALIDATORS service. Thanks to multi-parameter we won't override NG_VALIDATORS but just add CustomValidator to NG_VALIDATORS). Here's what you use’ @Directive ({ selector: '[CustomValidator]', providers: [iprovide: NG_VALIDATORS, useExisting: ustomValidator, multi:true}] » Example: @Directive({ tor: '[customValidation]', providers: [{provide: NG_VALIDATORS, useExistin true} EmailValidationDirective, mult » export class CustomValidation implements Validator { constructor() { } validate (control: AbstractControl): ValidationErrors { return ([Link] && [Link] <= 300) {myValue : true } : null; For multiple fields: validate (formGroup: FormGroup): ValidationErrors { const passwordControl - [Link][ "password" |; const emailControl = [Link]["Login"]; if (!passwordCont rol Ul lemailcontrol ![Link] || ![Link]) { return null; } if ([Link]. length [Link]) { [Link]({ tooLong: true }); ) else { [Link] (null); return formGroup; ngModel in Custom Component Add to module: providers: [ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextAreaComponent), multi: true Implement ControlValueAccessor interface rolValueAccessor { interface © writeValue(obj: any): void any): void registerOnChange ( erOnTouched(fn: any): void registerOnChange Register a function to tell Angular when the value of the input changes. registerOnTouched Register a function to tell Angular when the value was touched writeValue Tell Angular how to write a value to the input Sample implementation: Comp: a selector: 'app-text-area', templateUrl: './[Link]', styleUrls: ['./[Link] providers: [ provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => TextAreaCompone multi: true export class TextAreaComponent implements ControlValueAccessor, onInit { string; private _onChange = (data: any) => { [Link]('changed: ' + data); 3 private _onTouched = (data?: any) -> {[Link]('touched: * + data); de agonInit(): void { const self = this; constructor() {} writeValue(obj: any): void { [Link] = obj; registerOnChange(fn) { this._onChange = fns registerOnTouched(fn: any): void { this. _onTouched = fn; Tests Every software application under development needs to be tested to verify its correctness, and so do the Angular applications. Testing implies executing various tests or test cases on an application to validate it functionality and correctness. Unit tests Unit testing, in general, is a type of software testing level that checks various components of an application separately. In Angular, the default unit testing framework is Jasmine, It is widely utilized while developing an Angular project using CLI. Service describe ('MyService', () => { let service: MyService; Ve For async functions it("#fetch should update data’, (done: Don // some code done(); // we need 'done' to avoid test finishing before date was received // some code Ve ‘example async test mePn) => { => { expect (data) .toBe ("test"); done (); Spy and stub When you make calls during the testing process, a stub provides canned answers to all those calls. It does not respond to anything outside the program under test. Aspy is a stub that records the information based on the calls you make during the test. Spy: // create spied object by copy getDataAsyne from pService valueServiceSpy = jasmine. createSpy0bj ("ittpService', ['getDataAsyne']}; Stub: const Value = of ('StubValue'); ‘TestBed Mock whole module/environment for unit tests: beforeEach(() => { le! httpClientYock = Test Bed. configureTestingModule ({ providers: [i provide: MyService, —useValue: new pClientMock)}] })7 MyService ( Then use tested object (for example service) like this: service = TestBed. get (MyService) ; We can add schemas: [NO_ERRORS_SCHEMA]. This means that we don't have to mock child component dependencies of this component because Angular won't yell if we don't include them! Miscellaneous Http Interceptor An HTTP interceptor can handle any given HTTP request. Class: @Injectable() export class MyInterceptor implements littpInterceptor { constructor() { } intercept (reque: HttpRequest, next: HttpHandler): Observable> { // do sth (like check and throw error) xt. handle (request); //if want con Parameters: 1. req: HttpRequest - Its the object that handles outgoing requests. 2. next: Ht tpHlandler - It indicates the next interceptor in the line or the backend in case there are no incerptors. Returns: An HTTP interceptor returns the observable of the event stream Observable>

You might also like