来源
本文档直接取自GitHub30-seconds-of-angular项目。
Table of contents
Beginner snippets
- Accessing Enums in template
- Cheat Sheets and Checklists
- Component State Debugging
- Default ViewEncapsulation value
- hammerjs-gestures
- Loader Component
- ng-content
- ngIf else
- Optional parameters in the middle
- Renaming inputs and outputs
- Safe Navigation Operator
- trackBy in for loops
- Understanding Microsyntax
Intermediate snippets
- 来源
- Table of contents
- Beginner snippets
- Accessing Enums in template
- Cheat Sheets and Checklists
- Component State Debugging
- Default ViewEncapsulation value
- hammerjs-gestures
- Loader Component
- ng-content
- ngIf else
- Optional parameters in the middle
- Renaming inputs and outputs
- Safe Navigation Operator
- trackBy in for loops
- Understanding Microsyntax
- Intermediate snippets
- Accessing all nested form controls
- Adding keyboard shortcuts to elements
- Bind to host properties with host binding
- Component level providers
- Global event listeners
- Injecting document
- Mark reactive fields as touched
- Observables as outputs
- Passing template as an input
- Preseving whitespaces
- Reusing code in template
- Reusing existing custom pipes
- Style bindings
- Two-way binding any property
- Using APP_INITIALIZER to delay app start
- Window Location injection
- Advanced snippets
Advanced snippets
Beginner snippets
Accessing Enums in template
Enums are great but they are not visible in Angular templates by default.
With this little trick you can make them accessible.
1 | enum Animals { |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: enums templates
Cheat Sheets and Checklists
Check out Angular Cheat Sheet or (alternative version) containing lots of useful information condensed in one place.
Also Angular Checklist contains is curated list of common mistakes made when developing Angular applications.
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip cheat sheet
Component State Debugging
Debug the component state in the browser console by running:
1 | ng.probe($0).componentInstance |
$0
- is the DOM node currently selected in dev tools ($1
for the previous one and so on).
Bonus
With Ivy renderer engine:
1 | ng.getComponent($0) |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: good-to-know tips
Default ViewEncapsulation value
If you’re using ViewEncapsulation
value which is different than default, it might be daunting to set the value manually for every component.
Luckily you can configure it globally when bootstrapping your app:
1 | platformBrowserDynamic().bootstrapModule(AppModule, [ |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: configuration styling
hammerjs-gestures
To act upon swipes, pans, and pinhces as well as the other mobile gestures, you can use hammerjs
with HostListener
decorator, or an event binding,
1 | npm install hammerjs |
1 | 'swiperight') ( |
Bonus
Here are samples on how to use all of the hammerjs
event bindings, you can use these events with a HostListener
as well:
1 | <!-- pan events --> |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: good-to-know tips components gestures
Loader Component
You can create own helper component and use it instead of *ngIf
.
1 | ({ |
For usage example:
1 | <loader [loading]="isLoading">🦊 🦄 🐉</loader> |
Note that the content will be eagerly evaluated, e.g. in the snippet below
destroy-the-world
will be created before the loading even starts:
1 | <loader [loading]="isLoading"><destroy-the-world></destroy-the-world></loader> |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tips good-to-know components templates
ng-content
With ng-content
you can pass any elements to a component.
This simplifies creating reusable components.
1 | ({ |
1 | <wrapper> |
Links
https://medium.com/p/96a29d70d11b
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: good-to-know tips components
ngIf else
*ngIf
directive also supports else
statement.
1 | <div *ngIf="isLoading; else notLoading">loading...</div> |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: ngif templates
Optional parameters in the middle
Navigate with matrix params:
the router will navigate to /first;name=foo/details
1 | <a [routerLink]="['/', 'first', {name: 'foo'}, 'details']"> |
Links
https://stackblitz.com/edit/angular-xvy5pd
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: routing
Renaming inputs and outputs
In certain cases @Input
and @Output
properties can be named differently than the actual inputs and outputs.
1 | <div |
1 | selector: '[pagination]'}) ({ |
Note: Use this wisely, see StyleGuide recommedation
Links
https://angular.io/guide/styleguide#style-05-13
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: components templates
Safe Navigation Operator
The Safe Navigation Operator helps with preventing null-reference exceptions in component template expressions. It returns object property value if it exists or null otherwise.
1 | <p> I will work even if student is null or undefined: {{student?.name}} </p> |
Bonus
1 | {{a?.b?.c}} |
Underneath will be compiled to.
1 | (_co.a == null)? null: ((_co.a.b == null)? null: _co.a.b.c)); |
Links
https://github.com/angular/angular/issues/791
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: object property handling tips good to know
trackBy in for loops
To avoid the expensive operations, we can help Angular to track which items added or removed i.e. customize the default tracking algorithm by providing a trackBy option to NgForOf.
So you can provide your custom trackBy function that will return unique identifier for each iterated item.
For example, some key value of the item. If this key value matches the previous one, then Angular won’t detect changes.
trackBy takes a function that has index and item args.
1 | ({ |
If trackBy is given, Angular tracks changes by the return value of the function.
Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create/destroy only changed items.
Links
https://angular.io/api/common/NgForOf,https://angular.io/api/core/TrackByFunction
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: good-to-know tips components performance
Understanding Microsyntax
Under the hood Angular compiles structural directives into ng-template elements, e.g.:
1 | <!-- This --> |
The value passed to *ngFor directive is written using microsyntax. You can learn about it in the docs.
Also check out an interactive tool that shows the expansion by Alexey Zuev
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip structural directive microsyntax
Intermediate snippets
Accessing all nested form controls
Sometimes we need to work with every single Control is a form. Here’s how it can be done:
1 | function flattenControls(form: AbstractControl): AbstractControl[] { |
For examples use:
1 | // returns all dirty abstract controls |
Links
https://angular.io/guide/reactive-forms
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: reactive forms tips good to know
Adding keyboard shortcuts to elements
It’s really easy to add keyboard shortcuts in the template:
1 | <textarea (keydown.ctrl.enter)="doSomething()"></textarea> |
Bonus
1 | <input (keydown.enter)="..."> |
Links
https://alligator.io/angular/binding-keyup-keydown-events
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tips good-to-know
Bind to host properties with host binding
Every rendered angular component is wrapped in a host element (which is the same as component’s selector).
It is possible to bind properties and attributes of host element using @HostBinding decorators, e.g.
1 | import { Component, HostBinding } from '@angular/core'; |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: components
Component level providers
Generally we get one service instance per the whole application.
It is also possible to create an instance of service per component or directive.
1 | ({ |
1 | ({ |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tips components dependency-injection
Global event listeners
It is possible to add global event listeners in your Components/Directives with HostListener
. Angular will take care of unsubscribing once your directive is destroyed.
1 | ({ |
Bonus
You can have multiple bindings:
1 | 'window:keydown.ArrowRight') ( |
You can also pass params:
1 | 'window:keydown.ArrowRight', '$event.target') ( |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: events components
Injecting document
Sometimes you need to get access to global document
.
To simplify unit-testing, Angular provides it through dependency injection:
1 | import { DOCUMENT } from '@angular/common'; |
Links
https://angular.io/api/common/DOCUMENT
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: dependency injection
Mark reactive fields as touched
Here is the way to notify user that there are fields with non-valid values.
markFieldsAsTouched
function FormGroup or FormArray as an argument.
1 | function markFieldsAsTouched(form: AbstractControl): void { |
Bonus
It’s very useful to check out more general method Accessing all nested form controls by Thekiba to work with controls.
Links
https://angular.io/guide/reactive-forms
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: reactive forms validation tips good to know
Observables as outputs
EventEmitters
used for @Output
‘s are just Observables with an emit method.
This means that you can just use Observable
instance instead, e.g. we can wire up FormControl value changes directly:
1 | readonly checkbox = new FormControl(); |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip outputs
Passing template as an input
It’s possible to take a template as @Input
for a component to customize the render
1 | ({ |
1 | <site-menu [template]="menu1"></site-menu> |
Note:
ng-content
should be used for most of the cases and it’s simpler and more declarative.
Only use this approach if you need extra flexibility that can’t be achieved with ng-content.
Links
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: template
Preseving whitespaces
By default Angular strips all whitespaces in templates to save bytes. Generally it’s safe.
For rare cases when you need to preserve spaces you can use special ngPreserveWhitespaces
attribute:
1 | <div ngPreserveWhitespaces> |
You can also use preserveWhitespaces option on a component.
Links
https://twitter.com/mgechev/status/1108913389277839360
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip
Reusing code in template
While the best way of reusing your code is creating a component, it’s also possible to do it in a template.
To do this you can use ng-template
along with *ngTemplateOutlet
directive.
1 | <p> |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: templates
Reusing existing custom pipes
If you need a custom pipe
, before creating one, consider checking out the NGX Pipes package which has 70+ already implemeted custom pipes.
Here are some examples:
1 | <p>{{ date | timeAgo }}</p> |
Links
https://github.com/danrevah/ngx-pipes
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip pipes library
Style bindings
You can use advanced property bindings to set specific style values based on component property values:
1 | <p [style.background-color]="'green'"> |
Bonus
1 | <!-- Width in pixels --> |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: styles
Two-way binding any property
Similar to how you can two-way bind [(ngModel)]
you can two-way bind custom property on a component, for example [(value)]
. To do it use appropriate Input/Output naming:
1 | ({ |
Then you can use it as:
1 | <super-input [(value)]="value"></super-input> |
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip binding
Using APP_INITIALIZER to delay app start
It is possible to execute asynchronous task before the app start by providing a function returning promise using APP_INITIALIZER
token.
1 | ({ |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip
Window Location injection
For testing purposes you might want to inject window.location
object in your component.
You can achieve this with custom InjectionToken
mechanism provided by Angular.
1 | export const LOCATION_TOKEN = new InjectionToken<Location>('Window location object'); |
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: dependency-injection testing
Advanced snippets
Getting components of different types with ViewChild
It’s possible to use @ViewChild
(also @ViewChildren
and @ContentChild/Children
) to query for components of different types using dependency injection.
In the example below we can use @ViewChildren(Base)
to get instances of Foo
and Bar
.
1 | abstract class Base {} |
Links
https://www.youtube.com/watch?v=PRRgo6F0cjs
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: good-to-know tips components dependency-injection
Router Custom Preloading
Angular allows us to control the way module preloading is handled.
There are 2 strategies provided by @angular/router: PreloadAllModules
and NoPreloading
. The latter enabled by default, only preloading lazy modules on demand.
We can override this behavior by providing custom preloading strategy: In the example below we preload all included modules if the connection is good.
1 | import { Observable, of } from 'rxjs'; |
Note that that the example above would not be very efficient for larger apps, as it’ll preload all the modules.
Links
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: router
SVG
It is possible to use SVG tags in your Angular component, to create beautiful graphs and visualizations. There are 3 things you need to know:
- When binding an SVG attribute, use
attr
1
<circle [attr.cx]="x" [attr.cy]="y"></circle>
- When creating sub-components, use attribute and not tag selector:
1
2// Not: <child-component></child-component>
<g child-component></g>1
selector: '[child-component]' }) ({
- When using SVG tags in sub-components use svg prefix:
1
2
3
4({
selector: '[child-component]',
template: `<svg:circle></svg:circle>`
})
⭐ Interactive demo of this snippet | ⬆ Back to top | tags: tip SVG