Angular 2: The Art of Detecting Changes

I have successfully integrated Angular 1 and Angular 2 by creating an Angular 1 controller and service, along with an Angular 2 component. These components work seamlessly together for data retrieval and storage. Here is a snippet of my HTML page:

<body>
<h3>Angular 1 service</h3>
<div ng-controller="MainController">
    <input ng-model="username" />
    <button ng-click="setUser()">Set User</button>
    <button ng-click="getUser()">Get User</button>
    <div>User in service : {{user}}</div>
</div>
<hr>
<h3>Angular 2 component uses Angular 1 service</h3>
<user-section></user-section>
</body>

The MainController looks like this:

myApp.controller('MainController', function ($scope, UserService) {
    $scope.getUsers = function () {
        UserService.setUser($scope.username);
        window.location = './angular2.html'
    };

    $scope.setUser = function () {
        UserService.setUser($scope.username);
        $scope.user = $scope.username;
    };

    $scope.getUser = function () {
        $scope.user = UserService.getUser();
    };
});

The UserService code is as follows:

function UserService(){
    this.user = "default";
}

UserService.prototype.getUsers = function(){
    var users = ['user1', 'user2', 'user3'];
    return users;
}

UserService.prototype.setUser = function(usr){
    this.user = usr;
}

UserService.prototype.getUser = function(){
    return this.user;
}

And the Angular 2 component section:

    import {Component, Inject} from 'angular2/core';

    @Component({
        selector: 'user-section',
        templateUrl: '<div>
                      <input [(ngModel)]="username" />
                      <button (click)="setUser()">Set User</button>
                      <button (click)="getUser()">Get User</button>
                      <button (click)="getUsers()">Get Users</button>
                      <br/>
                      <ul>
                       <li *ngFor="#userId of users">{{userId}}</li>
                      </ul>
                      <div>User in service : {{user}}</div>
                      </div>'
   })
 export class UserSection {
        constructor(@Inject('UserService') userService:UserService) {
                this.users = [];
                this.username = '';
                this._UserService = userService;    
            }

        getUsers(){
            this.users = this._UserService.getUsers();
        }

        setUser(){
            this._UserService.setUser(this.username);
        }

        getUser(){
            this.user = this._UserService.getUser();
        }
    }

To update the Angular 2 model whenever the Angular 1 input changes, an event (getUser) must be fired consistently. You can check out a working example on Plunker here. If you want to make Angular 2 listen to changes in the Angular 1 service, there are listeners available in Angular 2 that can potentially serve this purpose, but the implementation might require further exploration.

Answer №1

Consider exploring the ngDoCheck and OnChanges lifecycle hooks in Angular2, as well as using $apply in your Angular1.

By utilizing $apply, you can modify your controller like this:

var myApp = angular.module("hybridExampleApp", []);

//define as Angular 1 service
myApp.service('UserService', UserService);

myApp.controller('MainController', function ($scope, UserService) {

   $scope.$watch('username',function(){
        $scope.setUser();
     });
    $scope.getUsers = function () {
        UserService.setUser($scope.username);
        window.location = './angular2.html'
    };

    $scope.setUser = function () {
        UserService.setUser($scope.username);
        $scope.user = $scope.username;
    };

    $scope.getUser = function () {
        $scope.user = UserService.getUser();
    };
});

When employing ngDoCheck, your user.section.component.ts file should be updated as shown below:

import {Component, Inject,ChangeDetectionStrategy,ngDoCheck,ngOnChanges} from 'angular2/core';

@Component({
    selector: 'user-section',
    templateUrl: './src/ng2-component/user.section.tpl.html',
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class UserSection implements ngDoCheck, ngOnChanges{

  username123:number;

constructor(@Inject('UserService') userService:UserService) {
        this.users = [];
        this.username = '';

        this.user=0;
        this._UserService = userService;
    }
    ngOnChanges(){
      console.log('adfkjna');

    }

    getUsers():void{
        this.users = this._UserService.getUsers();
    } 

    setUser():void{
        this._UserService.setUser(this.username);
    }

    getUser():void{ 
        this.user = this._UserService.getUser();
    }
     ngDoCheck(){

    this.user = this._UserService.getUser();
     this.getUser();
    console.log(this.user);

    }
}

Although my code successfully tracks changes in the username within Angular 1, I am encountering issues with binding it to the UI.

View a LIVE DEMO of your updated plunker.

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

Avoid making redundant ajax requests in AngularJS

I am currently utilizing express-jwt for constructing a restful api. The client is sending duplicate ajax calls - the first call initiated by AngularJS resulting in a 204 response code, and the second call initiated by another source resulting in a 200 res ...

Guide on how to address the problem of the @tawk.to/tawk-messenger-react module's absence of TypeScript definitions

Is there a way to fix the issue of missing TypeScript definitions for the @tawk.to/tawk-messenger-react module? The module '@tawk.to/tawk-messenger-react' does not have a declaration file. 'c:/develop/eachblock/aquatrack/management-tool-app ...

Adding additional properties to JSX components during typescript compilationIs there a way to include additional properties

Currently, I am employing JSX syntax in my TypeScript node.js project (without relying on React). Within my tsconfig, I have specified my custom jsxFactory { "compilerOptions": { ... "jsxFactory": "myJSXFactory", ...

How to deactivate an option in md-autocomplete

I encountered a scenario where I converted an md-input-container with a md-select/md-option to a md-autocomplete. While in the initial setup of md-select/md-option, we were able to apply ng-disabled property to both the md-select and md-option. However, wh ...

Angular - Mark all checkboxes on/off

My task involves implementing a specific functionality. I have three checkboxes, and when one is selected, I want the other two to be automatically selected as well. I am using a pre-built component to create these checkboxes. <form [formGroup]="d ...

How can I strategically close all open popovers in Angular UI Bootstrap?

In my table, I have a popover for each cell, similar to the example below: The code for the popover: <td ng-repeat="i in c.installments" ng-class="{ 'first' : i.first, 'last' : i.last, 'advance' : i.advance.value > 0, ...

Higher order components enhance generic components

I'm facing an issue where I want to assign a generic type to my React component props, but the type information gets lost when I wrap it in a higher order component (material-ui). How can I ensure that the required information is passed along? type P ...

What is the process for importing a function dynamically in a Next.js TypeScript environment?

Currently, I am utilizing a React modal library known as react-st-modal, and I am attempting to bring in a hook named useDialog. Unfortunately, my code is not functioning as expected and appears like this: const Dialog = dynamic<Function>( import(& ...

Updating Form Array Values in AngularLearn how to efficiently update values within a form

I am currently utilizing Angular8 and reactive forms. Here is my ngOnInit function: ngOnInit(): void { this.makeForm = this.fb.group( year: ['', Validators.required], amount: ['', Validators.required], desc: ['', ...

Socket.io allows us to broadcast messages to all users connected to the server using the "io

I've set up a MEAN app using npm socket.io with expressjs and btford.socket-io on the client side. angular.module('myApp',['btford.socket-io']) .factory('socket',function(socketFactory){ return socketFactory() ...

Memory usage of a Jhipster application running on an Amazon EC2 instance

My application is essentially an upscaled version of the default Jhipster app, lacking any form of cache implementation. I successfully deployed it on a t1.micro instance through Amazon's free tier option. I have been encountering sporadic 503 error ...

Troubleshooting Issue with Angular 5: Inability to Hide Elements for Non-Authenticated Users

Below is the code from app.component.html <nav class='navbar navbar-default'> <div class='container-fluid'> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-targ ...

Adjusting the return type based on the relationships defined in a Prisma object

Is there a way to implement a function that takes a Prisma object and dynamically sets the return type based on the included relations? I am aiming to type versionWithRelations with properties like pages, variables, and actions, while versionWithoutRelati ...

How to retrieve the content/value from a textfield and checkbox using HTML

I'm encountering an issue with my HTML code where I am unable to extract data from the HTML file to TS. My goal is to store all the information and send it to my database. Here is a snippet of the HTML: <h3>Part 1 : General Information</h3 ...

Issue: Module 'ansi-styles' not found when using AngularJS and Yeoman generator

Previously my code was functioning perfectly, but now it seems to have suddenly stopped working. Attempting yo angular:route api resulted in the following error message: Error: Cannot find module 'ansi-styles' at Function.Module._resolveFilen ...

The value of ng-repeat list in AngularJS does not update when its value is changed by an ajax call

I am completely perplexed. Why doesn't my ng-repeat update when there is an ajax call that changes its value? I have searched through many questions and answers here, but none of them address the issue with the ajax call. Here is the HTML: <div c ...

The 'pipe' property is not found on the 'Promise<HTTPResponse>' data type

Is there a way to fetch a list of products using an http call, apply pipe and map functions to the result, and then return it to the subscribed function? I am currently utilizing the ionic cordova advanced http plugin for SSL pinning in my requests. Howeve ...

ngSelect fails to load ajax data automatically upon page initialization

In my angular web application, I have a select element that is populated with data from an AJAX call. The issue I am facing is that the options in the select are not displayed until the select box is clicked on and then unfocused. Only after this action, a ...

Is it accurate to say that an Angular 6 build using the --prod flag results in a /dist folder that is 7 times larger

After completing my first production build, I noticed that it is 777kb in size. My /src file itself is 117kb. While I understand that the build size may increase due to dependencies, I have struggled to find reliable information online to determine if my b ...

Developing a union type to guarantee every value in the `enum` is accounted for

My code includes an enum that lists operations (which cannot be altered): enum OpType { OpA = 0, OpB = 1, } In addition, there are object types defined to hold data required for each operation: type A = { readonly opType: OpType.OpA; readonly foo: ...