A guide to implementing $scope.$watch in TypeScript

I am looking for a way to track changes in an element that is bound to my component. This element's value might change due to asynchronous calls, such as promises. In JavaScript, I typically use $scope.$watch to monitor the changes in the binding element and execute a callback function when it changes so I can work with the updated value.

Here's an example in JS:

$scope.$watch('myCtrl.myLayout', function (newVal, oldVal) {
    console.log('Layout is:');
    console.log(_this.myLayout);
});

angular.module('blocks.ui')
.component('myForm', {
    templateUrl: 'app/blocks/UI/form.html',
    controller: myForm,
    controllerAs: 'myCtrl',
    bindings: {
        myLayout: '='
    }
});

My question is, how can I achieve the same functionality using "clean" TypeScript syntax? I am aware that I can inject $scope and implement $scope.$watch in TypeScript in the same manner.

Thank you.

Answer №1

A recommended approach is to utilize TypeScript's get and set methods

private _myLayout:any;

public get MyLayout() {
   return this._myLayout;
}

public set MyLayout(newItem: any) {
    this._myLayout = newItem;
    console.log('The layout has been updated:');
    console.log(this.MyLayout);
}

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

Submitting an Ajax form refreshes the page

After submitting the form, the page reloads and I am trying to prevent that from happening. Latest Update: After receiving some feedback, I have made changes to my code. The form submission now works correctly, but the page still reloads. Previously, this ...

The issue with the angular-ui ui-calendar is that it does not reflect changes made to the Event Source Object or

I implemented fullcalendar.js into my angular app using angular-ui / ui-calendar. (angularjs 1.3.10, fullcalendar 2.2.6, ui-calendar 0.9.0-beta.1, jQuery 2.1.3, moment 2.9.0 & angular-moment 0.9.0) Within the calendar, I utilize the dayClick functio ...

What is the correct way to implement ng-click on an HTML element?

I'm facing a challenge with an HTML element that I don't have direct control over. Is there a method to include an ng-click event on it? For example: <div id="myDiv"><img src="my/img/src/jpg"/></div> What's the best way ...

What could be causing ng-repeat to malfunction?

My ng-repeat is not working with the table - only the header part is being displayed in the output. I have checked my binding and it seems to be correct, but I know I am missing something. Can someone please help me figure out what I am doing wrong? JAVA ...

Eliminate HTML TAG entries from the input form

My issue is that when I try to type a comma, it does not allow me to do so. How can I add other characters like <, >, /, \, etc? $("#in1").keypress(function (evt) { if (String.fromCharCode(evt.which) == ",") return false; }); < ...

Error: JSON response is returning as undefined

Whenever I attempt to display the height and weight data from an API (), I encounter an issue: Error: TypeError: Cannot read properties of undefined (reading 'metric') If I remove the "items.height.metric", everything runs smoothly, however, I ...

Performing a Node.js and Mongoose query to match an ID with values that are stored as a string separated by

Exploring the realms of Mongoose and NodeJS is a new venture for me. Within my product document, I am storing category ids in the following format: "reviewscount" : "2", "overallrating" : "4.5", "urlkey" : "strive-shoulder-pack", "productid" : "2", "cate ...

Error encountered: DataTable - Unable to retrieve the 'length' property of a null value

I am currently using a datatable in my project: function drawRadnici() { $('#tableradnici').dataTable({ "ajax": { "url": 'track_radnici.php', "type": 'POST' ...

Select the vocabulary items containing audio in an array using JavaScript

My goal is to enable clicking on words that are part of an array containing both texts and sounds. I found useful code at this link: Detect which word has been clicked on within a text. However, I am struggling to find a way to implement the feature of cl ...

Tips for building a JavaScript promise chain using an array function

I encountered a strange problem while working on a JS promise chain. When using an arrow function with parentheses in the promise, I am not getting the expected value. Instead, it gives me an 'undefined' value in the second 'then'. Her ...

AngularJS function that controls the transition to a different HTML page within an Android application

Within my index.html file, I have the following setup: <body background="img\loginback.jpg" ng-controller="SignInCtrl" > <button ng-click='signIn()'>SignUp</button> </body> In my app.js script, the code looks lik ...

What is the reason for compromising type safety when indexing in an array in TypeScript?

One of the main purposes behind incorporating static types into JavaScript is to offer assurances regarding type safety. I have observed that utilizing array indexing appears to compromise type safety without resorting to any deceptive techniques like as a ...

Leveraging jQuery for Crafting a Quiz with True or False Questions

Exploring the most effective approach to constructing a questionnaire. Find images below for reference. The current code setup is functional but becomes lengthy after just two questions. How can I streamline this code to minimize repetition? // prevent d ...

Utilizing Jquery in the Customer Portal feature within the Salesforce platform

Struggling to incorporate a Visualforce page with Jquery UI and Salesforce Customer Portal. Unfortunately, Jquery UI seems to be taking precedence over the Standard Salesforce stylesheet. Is there a way to prevent this from happening? Any assistance on t ...

What is preventing jQuery UI Sortable from functioning properly alongside Angular UI?

Using Angular UI and jQuery UI Sortable to replicate Connected Lists functionality has been challenging. The current implementation is not working smoothly. Any suggestions on how to improve it? Check out the behavior here: http://jsfiddle.net/hKYWr/227/ ...

Tips for choosing exclusively the visible content in search outcome

I'm working on a project that involves managing elements with checkboxes. I recently added a "checkAll" button to help select all elements at once. http://example.com/jsbin1 (edit) Any tips on enhancing user interface and ensuring only visible elem ...

Updating a nested subarray using Node.js with the MongoDB API

I am currently in the process of developing a backend API using Node.js/Express and MongoDB for managing student records. I am facing difficulty with updating a sub-field within the data structure. Below is the code snippet from my Student.js file located ...

Explain the TypeScript type where the keys of an object not found in an array should correspond to the type of another object

Currently, I am developing a utility function called copyKnownProperties that is responsible for copying properties from one class or object to another only if the key exists on both objects. In the example provided, you can observe an attempt to copy prop ...

Creating a jQuery countdown script

Is it possible to easily convert the function below into jQuery and still maintain the ability to call multiple instances of the countdown? This particular function receives a server time echoed by the server and then initiates a countdown to the specifie ...

Difficulty selecting lines in Angular ui-grid

Having trouble selecting the first rendered line with Angular ui-grid. I've tried various methods, including utilizing a timeout after rendering data from the server. Here is an example on Plunker. I attempted using the code snippet below but it' ...