You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classMyComponent{constructor(){}
@Input()prop : number;ngOnChanges(changes: SimpleChanges){// Return: viod, Params: @angular/core/SimpleChanges - The changed properties. // changes.prop contains the old and the new value...}ngOnInit(){// Return: viod, Params: no params.}ngDoCheck(){// Return: viod, Params: no params.}ngAfterContentInit(){// Return: viod, Params: no params.}ngAfterContentChecked(){// Return: viod, Params: no params.}ngAfterViewInit(){// Return: viod, Params: no params.}ngAfterViewChecked(){// Return: viod, Params: no params.}ngOnDestroy(){// Return: viod, Params: no params.}}
When to use Lifecycle Hooks
constructor vs ngOnInit
constructor() to setup Dependency Injection and not much else. ngOnInit() is for all the initialization/declaration and avoid stuff to work in the constructor. constructor() - A class constructor in Angular is mostly used to inject dependencies. ngOnInit() - ngOnInit is purely there to give us a signal that Angular has finished initialising the component. It is to perform initialization logic even if this logic doesnโt depend on DI, DOM or input bindings.
Be careful on the logic that you put in your constructor because may depend on that is not available yet. Data is not always immediately available in the constructor, so it should do no more than set the initial local variables to simple values. Divide all the initial logic between the three Init hooks. The ngOnInit is a good place for a component to fetch its initial data;
ngOnChanges vs ngDoCheck
as we said ngOnChanges is called when a value bound to an input has changed so you can run custom code when an input has changed. ngDoCheck to the other hand is called when change detection runs so you can implement your custom change detection action, but be careful on using it because will run all the time there is a change detection and user experience will suffer;
ngAfterContentInit vs ngAfterViewInit
use ngAfterContent when you want to use the power of Query like @ContentChildren ( Content projection is a way to import HTML content from outside the component and insert that content into the componentโs template in a designated spot, also as known as transclusion). Instead use ngAfterViewInit for any initialization that needs the view be rendered like jQuery plugin or simple external DOM manipulations, this will avoid you use setTimeout in most of the other hooks;
ngAfterContentChecked vs ngAfterViewChecked
both hooks has to be used carefully and have a lightweight implementation because every time happen a change detection these hooks are going to be called;
ngOnChanges vs ngAfterViewChecked
there is mostly two type of components, the reusable one, and the unique one. The reusable one uses more ngOnChanges the unique could use also the power of ngAfterViewCheck. So it is important to understand when ngOnChanges fires and when ngAfterViewCheck fires.
ngOnDestroy
This method will be invoked just before Angular destroys the component.
Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.
A component directive requires a view along with its attached behaviour. The component directive adds DOM elements, that have a template.
2. Structural Directives
Modifies the DOM layout by adding and removing DOM elements.
Rather than adding new DOM elements, these types of directives modify the existing DOM and do not have templates.
TemplateRef represents an embedded template that can be used to instantiate embedded
ViewContainerRef
ViewContainerRef represents a container where one or more views can be attached.
*ngfor - trackBy: fnName
We can help Angular to track which items added or removed by providing a trackBy function.
The trackBy function takes the index and the current item as arguments and needs to return the unique identifier for this item.
If you change the input data collection, Angular can track which items have been added or removed according to the unique identifier and create or destroy only the things that changed.
Modifies the appearance or behavior of an element. Rather than adding new DOM elements, these types of directives modify the existing DOM and do not have templates.
An ElementRef is backed by a render-specific element. In the browser, this is usually a DOM element.
Renderer
Angular renders a template into DOM.
Use a custom renderer to bypass Angular's templating and make custom UI changes that can't be expressed declaratively.
@HostBinding - Property Bind
The @HostBinding decorator a directive can link an internal property to an input property on the host element. So if the internal property changed the input property on the host element would also change.
@HostListener - AddEventListener
This is a function decorator that accepts an event name as an argument. When that event gets fired on the host element it calls the associated function.
We cann't remove @HostListener, i.e. can't remove event listener.
An Angular service is a singleton - which means it is instantiated only ONCE. It is also injectable which means it can be used throughout your application. It is instantiated at the start of the application and is available throughout the lifetime of the application.
Pure Pipe - Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property. Pure Pipe produce the same output when invoked with the same set of arguments.
Example: DatePipe, UpperCasePipe and LowerCasePipe
Impure Pipe - Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.
Example: JsonPipe and SlicePipe
Stateful Pipes vs Stateless Pipes
Stateless pipes are pure functions that flow input data through without remembering anything or causing detectable side-effects. Most pipes are stateless.
Stateful pipes are those which can manage the state of the data they transform. A pipe that creates an HTTP request, stores the response and displays the output, is a stateful pipe. Stateful Pipes should be used cautiously.
Chaining pipes
We can chain pipes together to make use of multiple pipes in one expression.
canActivate is used to prevent an unauthorized user
canLoad is used to prevent the entire module of app
canActivate - Code is downloaded.
canLoad - Code will not get downloaded. canLoad used for LazyLoaded Modules.
The CanLoad guard blocks loading of feature module assets until authorized to do so. If you want to both preload a module and guard against unauthorized access, use the CanActivate guard instead.
Angular FORM supports two-way data binding, change tracking, validation, and error handling.
Using this we can lay out the controls creatively, bind them to data, specify validation rules and display validation errors, conditionally enable or disable specific controls, trigger built-in visual feedback, and much more.
Attributes
novalidate
novalidate attribute is used to disable browser's native form validation.
If you want to use native validation with Angular forms, just add ngNativeValidate.
ngNoForm
When you add ngNoForm, you turn off Angular's form registration helpers. In other words, the NgForm directive is never activated. This is the directive that knows how to interact with custom value accessors. Without it, you're just using HTML5 forms at the top level, which of course won't know anything about your custom input. This is expected behavior for ngNoForm, so I'm going to close this.
๐Reference.
Template Driven FORM
In the template-driven approach the form structure and logic is mainly implemented in HTML. Based on this a representation of the form in TypeScript is generated automatically.
The structure and logic of a form is fix.
The number of form fields does not vary
Form validation rules are the same for different user roles.
ngForm
ngSubmit
ngModelGroup
ngModel
ngModel Validation CSS Classes
ng-touched: Control has been visited
ng-untouched: Control has not been visited
ng-dirty: Control's value has been changed
ng-pristine: Control's value hasn't been changed
ng-valid: Control's value is valid. Valid for maxLength, minLength, pattern and required.
ng-invalid: Control's value isn't valid
๐ Examples:
Login forms, Reset password forms, Forms to enter and edit Address data, Order data and similar fix data structures.
Handling events when the components are distinct until changed.
Adding elements dynamically.
Results in a better testable form by leveraging a decoupling between the HTML (design/CSS team can work here) and component's business rules.
To improve the user experience with features like reactive transformations, correlated validations and handle complex scenarios as runtime validation rules.
ReactiveFormsModule
FormControl
An individual form input, checkbox, select, textarea, etc.
FormGroup
A group of form fields that can be manipulated and validated together.
NgZone is basically a forked zone that extends its API and adds some additional functionality to its execution context. One of the things it adds to the API is the following set of custom events we can subscribe to, as they are observable streams:
NgZone.onTurnStart() ==> NgZone.onUnstable() - Notifies subscribers just before Angularโs event turn starts. Emits an event once per browser task that is handled by Angular.
NgZone.onTurnDone() ==> NgZone.onMicrotaskEmpty() - Notifies subscribers immediately after Angularโs zone is done processing the current turn and any micro tasks scheduled from that turn.
NgZone.onEventDone() => NgZone.onStable() - Notifies subscribers immediately after the final onTurnDone() callback before ending VM event. Useful for testing to validate application state.
zone.js
Zones is a new mechanism that helps developers work with multiple logically-connected async operations. Zones work by associating each async operation with a zone.
Without zones, we donโt get any change detection, so we donโt get any of the nice UI updates that weโd expect!
A developer can take advantage of this binding to:
Associate some data with the zone, analogous to thread-local storage in other languages, which is accessible to any async operation inside the zone.
Automatically track outstanding async operations within a given zone to perform cleanup or rendering or test assertion steps
Time the total time spent in a zone, for analytics or in-the-field profiling
Handle all uncaught exceptions or unhandled promise rejections within a zone, instead of letting them propagate to the top level