Angular Cheat Sheet 1685351904
Angular Cheat Sheet 1685351904
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.
In this Angular CLI commands cheat sheet section, we’ll cover various Angular CI
commands.
1. Setup
2. New Application
ng new --help
ng lint my-app
If you want to format the code, you can use the following command.
ng lint my-app --format stylish
4. Blueprints
Generate spec:
--spec
--inline-template (-t)
--inline-style (-s)
Create a directive:
ng g d directive-name
Create a pipeline:
ng g p init-caps
ng g cl models/customer
Creates a component without the need for the creation of a new folder.
Assign a prefix:
--prefix
Create an interface in the models folder:
ng g i models/person
ng g e models/gender
Create a service:
ng g s service-name
5. Building Serving
ng build
ng build --aot
ng build --prod
ng serve -o
ng serve --live-reload
ng serve -ssl
6. Add New Capabilities
ng add @angular/material
@Component({
// component attributes
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.less']
})
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.
moduleId
The module ID of the module that contains the component.
encapsulation
An encapsulation policy for the template and CSS styles.
interpolation
Overrides the default encapsulation start and end delimiters ({{ and }}.
entryComponents
A set of components that should be compiled along with this component.
preserveWhitespaces
True to preserve or false to remove potentially superfluous whitespace characters from
the compiled template.
ngOnInit
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 ngAfterViewInit() and every subsequent ngAfterContentChecked().
ngAfterContentInit
Called once after the first ngDoCheck().
ngAfterViewInit
Called once after the first ngAfterContentChecked().
Template Syntax
{{user.name}}
Interpolation - generates user name.
<app-my-component
(myEvent)="someFunction()"></app-my-component>
Content Projection
Content projection in Angular is a pattern in which you inject the desired content into a
specific component.
<component>
<div>
(some html here)
</div>
</component>
<ng-content></ng-content>
Let us now inject the following HTML code in the parent component template:
<div well-body>
(some html here)
</div>
<component>
<div well-title>
(some html here)
</div>
<div well-body>
(some html here)
</div>
</component>
When we combine both the above parent and child template, you get the following
result:
<component>
<div well-title>
(some html here)
</div>
<div well-body>
(some html here)
</div>
</component>
<ng-content select="title"></ng-content>
<ng-content select="body"></ng-content>
ViewChild Decorator
Offers access to child component/directive/element:
@ViewChild(NumberComponent)
private numberComponent: NumberComponent;
increase() {
this.numberComponent.increaseByOne(); //method from child
component
}
decrease() {
this.numberComponent.decreaseByOne(); //method from child
component
}
Sample for element: html:
<div #myElement></div>
component:
Routing
The Angular Router enables navigation from one view to the next as users perform
application tasks.
RouterModule.forRoot(appRoutes)
You can also turn on console tracking for your routing by adding enableTracing:
imports: [
RouterModule.forRoot(
routes,
{enableTracing: true}
)
],
Usage
<a routerLink="/crisis-center" routerLinkActive="active">Crisis
Center</a>
routerLinkActive="active" will add active class to element when the link's route becomes
active
// with parameters
CanActivate:
class UserToken {}
class Permissions {
canActivate(user: UserToken, id: string): boolean {
return true;
}
}
CanDeactivate:
class UserToken {}
class Permissions {
canDeactivate(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.
@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.
@Injectable()
export class MyService {
public items: Item[];
constructor() { }
getSth() {
// 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:
providers: [MyService]
HttpClient
This command handles and consumes http requests.
...
// GET
// POST
Dependency Injection
@Injectable({
providedIn: 'root',
})
Class:
Module:
constructor(@Optional() @Inject(CONTROLS_GLOBAL_CONFIG)
globalVlues: ControlsConfig) {
Pipes
{{model.birthsDay | date:'shortDate'}}
Pipe implementation:
@Pipe({name: 'uselessPipe'})
usage:
Directives
An Attribute directive changes A DOM element’s appearance or behavior. For example,
[ngStyle] is a directive.
Custom directive:
@Directive({
selector: '[appHighlight]'
})
@HostListener('mouseenter') onMouseEnter() {
this.highlight(this.highlightColor || 'red');
this.el.nativeElement.style.backgroundColor = color;
Usage:
Animations
Animations allow you to move from one style state to another before adding
BrowserModule and BrowserAnimationsModule to the module.
Implementation:
animations: [
trigger('openClose', [
state('open', style({
height: '400px',
opacity: 1.5,
})),
state('closed', style({
height: '100px',
opacity: 0.5,
})),
animate('1s')
]),
animate('1s')
])
])
Usage
Angular Forms
In this section of our Angular 4 cheat sheet, we’ll discuss different types of Angular
forms.
Template Driven Forms
sample html
<div
*ngIf="firstName.errors.required">First Name is required</div>
</div>
</div>
<div class="form-group">
<button class="btn
btn-primary">Register</button>
</div>
</form>
Sample component:
@ViewChild("f") form: any;
onSubmit() {
if (this.form.valid) {
console.log("Form Submitted!");
this.form.reset();
Reactive Forms
Sample HTML:
<div class="form-group">
</div>
</form>
Sample component:
registerForm: FormGroup;
submitted = false;
ngOnInit() {
this.registerForm = this.formBuilder.group({
onSubmit() {
this.submitted = true;
if (this.registerForm.invalid) {
return;
alert('SUCCESS!! :-)')
Function:
validateUrl(control: AbstractControl) {
if (!control.value || control.value.includes('.png') ||
control.value.includes('.jpg')) {
return null;
Usage:
this.secondFormGroup = this._formBuilder.group({
});
Multi-field validation:
validateNameShire(group: FormGroup) {
if (group) {
if (group.get('isShireCtrl').value &&
!group.get('nameCtrl').value.toString().toLowerCase().includes('
shire')) {
return null;
this.firstFormGroup.setValidators(this.validateNameShire);
Error handling:
<div
*ngIf="firstFormGroup.controls.nameCtrl.errors.maxlength">Name
is too long</div>
<div *ngIf="firstFormGroup.errors.nameShire">Shire dogs should
have "shire" in name</div>
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).
@Directive({
selector: '[CustomValidator]',
})
Example:
@Directive({
selector: '[customValidation]',
})
if (!passwordControl || !emailControl ||
!passwordControl.value || !emailControl.value) {
return null;
if (passwordControl.value.length >
emailControl.value.length) {
} else {
passwordControl.setErrors(null);
return formGroup;
}
Add to module:
providers: [
provide: NG_VALUE_ACCESSOR,
multi: true
interface ControlValueAccessor {
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:
@Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
styleUrls: ['./text-area.component.less'],
providers: [
provide: NG_VALUE_ACCESSOR,
multi: true
})
ngOnInit(): void {
constructor() {}
this.value = obj;
registerOnChange(fn) {
this._onChange = fn;
this._onTouched = fn;
}
Tests
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', () => {
service.fetchData();
expect(service.data.length).toBe(4);
expect(service.data[0].id).toBe(1);
});
});
// some code
done(); // we need 'done' to avoid test finishing before
date was received
// some code
});
service.getUser().subscribe((data) => {
expect(data).toBe('test');
done();
});
});
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.
A spy is a stub that records the information based on the calls you make during the test.
Spy:
const valueServiceSpy =
jasmine.createSpyObj('HttpService', ['getDataAsync']);
Stub:
valueServiceSpy.getDataAsync.and.returnValue(stubValue);
beforeEach(() => {
});
service = TestBed.get(MyService);
Miscellaneous
Http Interceptor
Class:
@Injectable()
Parameters:
Returns:
Observable<HttpEvent<any>>