The value of the local variable remained unchanged despite the occurrence of global events (window.onresize)

The value of the local variable remained unchanged despite global events (window.onresize) occurring.

export class TestComponent implements OnInit {
    a: number = 0;
    b: number = 0;
    ngOnInit() {
        window.onresize = () => {
            this.a = 10;
            this.b = 10;
        };
    }
}

https://i.sstatic.net/7IOEw.png

Answer №1

Connect to global events by utilizing host binding, as outlined in the API documentation. You can find more information about this in the DirectiveMetadata page:

@Component({
  selector: 'my-app',
  template: `<p>Resize window and observe console log.
    <p>{{a}} {{b}}`
})
export class AppComponent {
  @HostListener('window:resize') onResize() {
    this.a++;
    this.b++;
    console.log(this.a, this.b, event)
  }
}

plunker

Your original code fails because you overwrote the onresize handler (which Angular had also modified) with your own function. As a result, Angular loses the ability to perform change detection after the event handler completes. By using host binding, you ensure that the Angular monkey-patch remains intact, preventing the disabling of change detection so that your view updates seamlessly after the resize event.

Answer №2

The value of the local variable remained unchanged.

Upon review of the screenshot, it is evident that this.b = 10, thereby indicating a change in the variable's value.

https://i.sstatic.net/jK8EN.png

The screenshot also displays a: number = 0. This simply shows the value of a at the last breakpoint. It is also noticeable that this.a is 10

Answer №3

After encountering a similar issue, I managed to resolve it by ensuring that the update code ran within the Angular Zone. I found helpful documentation that guided me through the process, which is available at https://angular.io/docs/js/latest/api/core/index/DirectiveMetadata-class.html (up to date as of 10/8/16).

You can implement a solution similar to the following:

import {Component, OnInit, NgZone} from '@angular/core';

constructor(private _ngZone: NgZone) {
}

ngOnInit() {
    window.onresize = () => {
        this._ngZone.run(() => {
            this.a = 10;
            this.b = 10;
        }
    };
}

Although simpler than the solution provided by Mark Rajcok in another discussion, it's worth noting that Angular 2 is continuously evolving. Therefore, my approach may be one of the improvements that have been implemented, as the link to DirectiveMetadata may no longer be relevant.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: Parsing error in Typescript eslint - The use of the keyword 'import' is restricted

My CDK application is written in typescript. Running npm run eslint locally shows no errors. However, when the same command is executed in a GitLab pipeline, I encounter the following error: 1:1 error Parsing error: The keyword 'import' is r ...

Make sure to name your Typescript component selector correctly, as it should not

As I work on my Angular project, I encountered a situation where one component needed to be referenced in the HTML of another component. To make this connection, I used kebab case for the selector like so: @Component({ selector: 'swiftlog-navbar&ap ...

Incorporating CASL with the latest version of Angular, version

I'm currently working on implementing CASL into my Angular application, but I'm having trouble understanding how to integrate it. // Login Component ngOnInit() { var jsonBody = {}; jsonBody['email'] = 'peter@klaven'; ...

Issue encountered when attempting to display JSON index on individual result page

This is a JSON response. { "listing": { "id": "1", "name": "Institute Name", "contact": "9876543210", "website": "http://www.domain.in", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" da ...

Challenge encountered with implementing Next-Auth's authorize function in TypeScript

Encountering a type error in the authorize function while using NextAuth with CredentialsProvider export const authOptions : NextAuthOptions ={ session : { strategy: "jwt" }, providers : [ CredentialsProvider({ async authorize( c ...

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Is there an array containing unique DateTime strings?

I am dealing with an Array<object> containing n objects of a specific type. { name: 'random', startDate: '2017-11-10 09:00', endDate: '2017-11-23 11:00' } My goal is to filter this array before rendering the resu ...

Exploring the Potential of Jest Testing for Angular 6 Services

Hey there, I seem to be facing a bit of a roadblock and could use some assistance. Here's the situation - I'm trying to test a service using Jest, but all the tests pass without any issues even when they shouldn't. Here are the details of t ...

tslint issues detected within a line of code in a function

I am a novice when it comes to tslint and typescript. Attempting to resolve the error: Unnecessary local variable - stackThird. Can someone guide me on how to rectify this issue? Despite research, I have not been successful in finding a solution. The err ...

What do you think about gulp-typescript and the latest @types typings for TypeScript?

I've added @types/jasmine as a development dependency. This is my gulp task for compiling TypeScript: gulp.task('compile:tests', ['compile:typescript', 'clean:tests'], function () { var project = ts.createProject(&a ...

When the page is first loaded, the select options dropdown using NgFor and NgValue does not display the initial object from the list

I am facing an issue with a select options dropdown that contains a list of objects. I have used ngValue to set the value of the dropdown as an object. However, upon page load, the dropdown does not display the first object from the list; it only shows obj ...

Obtaining the ViewRef of the current component in Angular 4

How can I obtain the ViewRef for my current component? I am attempting to retrieve the ViewRef from a service. Below is the code: component.service.ts import { Injectable, ViewRef } from '@angular/core'; @Injectable() export class CheckboxSe ...

The properties are absent in Angular Service - Observable

I recently started learning angular and I'm struggling to make this HTTP get request work. I have been looking at various examples of get requests for arrays and attempted to modify one for a single object (a user profile) but without success. The err ...

How is it possible for the igx-expansion-panel to close when there is a nested angular accordion present?

Currently, I am faced with the challenge of closing the igx-expansion-panel within my Angular project. While everything functions smoothly with a standard panel, things get a bit tricky when dealing with nested angular accordion structures using igx-accord ...

Using TypeScript and the `this` keyword in SharePoint Framework with Vue

I'm currently developing a SharePoint Framework web part with Vue.js. Check out this code snippet: export default class MyWorkspaceTestWebPart extends BaseClientSideWebPart<IMyWorkspaceTestWebPartProps> { public uol_app; public render(): ...

Is it possible to dynamically load the child path of the Foo Component from a separate component using the current route data?

What I am in need of: The application includes a side-nav component, which contains a menu to load features and a sub-menu to load sub-features. Sub-features are considered as child routes of features. I have attempted to utilize a sample application wit ...

Dynamic Angular select options with ngFor causing cascading changes in subsequent selects

In my Angular 5 project, I am attempting to create a set of three <select> elements using *ngFor. I came across a helpful thread on Stack Overflow that provided some guidance (check it out here). However, I've encountered an issue where the sele ...

Sending a style prop to a React component

My typescript Next.js app seems to be misbehaving, or perhaps I'm just not understanding something properly. I have a component called <CluckHUD props="styles.Moon" /> that is meant to pass the theme as a CSS classname in order to c ...

Validation of time input using Angular Material within a ReactiveForm

Currently immersed in Angular 17 along with Material theme, I find myself faced with a scenario involving Reactive Forms housing two time-input fields. The array [minHour, maxHour] should represent a range of Hours, let's say [09:00 , 13:00]. HTML [ ...

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...