functionaddEventListener(eventName, callback) { // call the real addEventListener callRealAddEventListener(eventName, function() { // first call the original callback callback(...); // and then run Angular-specific functionality var changed = angular.runChangeDetection(); if (changed) { angular.reRenderUIPart(); } }); }
Take the DOM event as an example, when user click a button on page, Angular will run change detection to update the view. Angular will run change detection after the event handler is executed.
Here is the pseudo code, you can find the real code in packages/zone.js/lib/browser/event-target.ts in angular source code.(Note, initially, zone.js is a independent library, but it is moved to angular’s mono-repo.)
1 2 3 4 5 6 7 8 9 10 11
// Store a reference to the original addEventListener const nativeAddEventListener = window.EventTarget.prototype.addEventListener;
// Replace the original addEventListener with a patched version window.EventTarget.prototype.addEventListener = function(eventName, handler, options) { // Call the native addEventListener with the provided arguments nativeAddEventListener.call(this, eventName, handler, options);
// Additional functionality to track the state of asynchronous operations // This could involve interacting with Zone.js's internal data structures };
Change Detection steps
An event occurs (user action, timer, AJAX response, etc.).
Angular’s zone (NgZone) notifies Angular that an async operation has completed.
Angular triggers change detection starting from the root component.
For each component, it checks the template bindings against the current component state.
If a binding has changed, Angular updates the DOM accordingly.
Components using OnPush strategy only check if their inputs have changed or if marked explicitly.
The process continues down the component tree until all components are checked.
Angular uses NgZone to detect changes in the application. NgZone is a class that provides a way to run code in the Angular zone. It is used to detect changes in the application.
You can easily see NgZone by logging it to the console.
You can use the ngDoCheck lifecycle hook to determine when change detection is triggered in a component. ngDoCheck is called every time change detection is triggered in a component.
ngOnChanges is a lifecycle hook that is called when a component’s input properties change. It is used to detect changes in the component’s input properties.
What’s the scenarios to use ngOnChanges?
When you want to detect changes in the component’s input properties.
When you want to avoid function call in template. see here
Extract the downloaded file to a folder, for example, C:\nginx.
Build your app
Build your Angular app using the following command: This will generate the dist folder under your project root. for example, D:\codes\angular\angular-router.
1
ng build --prod
Setup Nginx
Open a command prompt as an administrator.
Navigate to the Nginx directory.
Open the conf/nginx.conf file in a text editor.
Find the http | server block and add the following line:
1 2 3 4 5 6 7 8
server { listen80; server_name localhost; location / { root D:/codes/angular/angular-router/dist; index index.html index.htm; } }
Start Nginx
Open a command prompt as an administrator.
Navigate to the Nginx directory.
Start Nginx using the following command:
1
start nginx
Restart Nginx
1
nginx -s reload
Stop Nginx
1
nginx -s stop
Check Nginx configuration
1
nginx -t
If the configuration is valid, you will see a message like this:
1 2
nginx: the configuration file C:/nginx/conf/nginx.conf syntax is ok nginx: configuration file C:/nginx/conf/nginx.conf test is successful
<!-- parent.component.html --> <p>I'm Father, my name is: {{ name }}</p> <app-child (onChangeName)="changeName($event)" [age]=30 [name]="'Philip'"></app-child>
Then we update the name property in child component.
Run the application, you will see the error in the console.
1
core.mjs:9171 ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'Tom'. Current value: 'Jerry'
Conclusion
There are several scenarios that produce this error.
value in ngAfterViewInit.
Use random values in template bindings
Update parent component property from child component.
How to solve this problem
Refactor ngAfterViewInit lifecycle hook.
Use ChangeDetectorRef to manually trigger change detection.
Posted onEdited onInangular Symbols count in article: 657Reading time ≈2 mins.
你也许在Angular的文档或者某些博客中看到过这样一句话: Every application has at least one Angular module, the root module, which must be present for bootstrapping the application on launch. By convention and by default, this NgModule is named AppModule
@Component({ standalone: true, // set standalone to true selector: 'app-root', imports: [RouterModule], // import RouterModule if you use router templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) exportclassAppComponent { title = 'angular-router'; }
Angular elements are Angular components packaged as custom elements (also called Web Components), a web standard for defining new HTML elements in a framework-agnostic way
注意这里discount属性是可选的,因为我们在getPrice方法中判断了discount是否存在,如果不存在就抛出异常。这样做是为了防止忘记设置折扣而导致的错误。如果不设置为可选的话会报错:Property 'discount' has no initializer and is not definitely assigned in the constructor. 由于TypeScript配置文件默认开启了strictPropertyInitialization选项导致的。
Sorting Algorithms: If you have a collection of data that can be sorted in several ways, you can use the Strategy pattern to switch between sorting algorithms (like quicksort, merge sort, heap sort) at runtime.
Payment Methods: In an e-commerce application, you can use the Strategy pattern to switch between different payment methods (like credit card, PayPal, Bitcoin) at runtime.
Compression Algorithms: If you have a file that can be compressed using different algorithms (like zip, rar, 7z), you can use the Strategy pattern to choose the compression algorithm at runtime.
Travel Planning: If you have a travel planning application, you can use the Strategy pattern to switch between different travel strategies (like by car, by train, by plane) at runtime.