Showing posts with label angular. Show all posts
Showing posts with label angular. Show all posts

09 October, 2022

Error: Cannot assign value "$event" to template variable "emailBody". Template variables are read-only.

 Error: Cannot assign value "$event" to template variable "emailBody". Template variables are read-only.


First of all, binding ngModel to your local variable X from.ts is not possible using #emailBody="ngModel."

A new template variable emailBody will be bound to the instance of the Angular directive ngModel, which has nothing to do with your.ts variable. The only place a template variable may be found is in your component's.html (unless you use @ViewChild or a similar method to retrieve a reference in your.ts).


Here is old cod that has this issue :

 <div class="ed_contact_form ed_toppadder60 row m-0">
        <div class="col-lg-6 col-md-6 col-sm-12">
          <div class="form-group">
            <input type="text" id="uname" class="form-control"
                    placeholder="Your Name">
          </div>
          <div class="form-group">
            <input type="email" id="fromEmail" class="form-control"
            placeholder="Your Email" name="fromEmail" #fromEmailt="ngModel"
                [(ngModel)]="fromEmail">
          </div>
          <div class="form-group">
            <input type="text" id="emailSubject" class="form-control"
            placeholder="emailSubject" required #emailSubject="ngModel"
            [ngModel]="emailSubject">
          </div>
        </div>
        <div class="col-lg-6 col-md-6 col-sm-12">
          <div class="form-group">
            <textarea id="emailBody" class="form-control" rows="6"
                placeholder="emailBody" required  #emailBody="ngModel"
                [(ngModel)]="emailBody"></textarea>
          </div>
         
        </div>


New Codde Ater Fixes 

your component variable name, and directive name should not be the same. 

to fix it I have added #emailBoddy instead of #emailBody.

<div class="ed_contact_form ed_toppadder60 row m-0">
  <div class="col-lg-6 col-md-6 col-sm-12">
    <div class="form-group">
      <input type="text" id="uname" class="form-control"
              placeholder="Your Name">
    </div>
    <div class="form-group">
      <input type="email" id="fromEmail" class="form-control"
      placeholder="Your Email" name="fromEmail" #fromEmailt1="ngModel"
          [(ngModel)]="fromEmail">
    </div>
    <div class="form-group">
      <input type="text" id="emailSubject" class="form-control"
      placeholder="emailSubject" required #emailSubject1="ngModel"
      [ngModel]="emailSubject">
    </div>
  </div>
  <div class="col-lg-6 col-md-6 col-sm-12">
    <div class="form-group">
      <textarea id="emailBody" class="form-control" rows="6"
          placeholder="emailBody" required  #emailBody1="ngModel"
          [(ngModel)]="emailBody"></textarea>
    </div>
   
  </div>




23 September, 2022

Angular 14 function inside callback value not updating view

 Angular 14 function inside callback value not updating view

I've written a function, inside of which I'm calling a callback function. After the callback answer, I updated a string variable, but my view was not updated.

Old Code


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

@Component({
  selector: 'app-appointment',
  templateUrl: './appointment.component.html',
  styleUrls: ['./appointment.component.css']
})


export class ViewComponent {

        getAddress : string;
        public totlaBalance : string;

        ngOnInit():void{
             var self = this;
             fetchData(this.getEmployees,function(error,res){
                 console.log(res);
                 self.totlaBalance = res;

            });
        }
}


Solution 1 (new Code):

Just need to use ArrowFunction (()=>) and  call the method ChangeDetectionRef as shown below,



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

@Component({
  selector: 'app-appointment',
  templateUrl: './appointment.component.html',
  styleUrls: ['./appointment.component.css']
})


export class ViewComponent {

        getAddress : string;
        public totlaBalance : string;

        constructor(private ref: ChangeDetectorRef){}  

        ngOnInit():void{
             var self = this;
             fetchData(this.getEmployees,function(error,res){
                 console.log(res);
                 self.totlaBalance = res;
                 self.ref.detectChanges();

            });
        }
}


Solution 2: NgZone

An injectable service for executing work inside or outside of the Angular zone.


The most common use of this service is to optimize performance when starting a work consisting of one or more asynchronous tasks that don't require UI updates or error handling to be handled by Angular. Such tasks can be kicked off via runOutsideAngular and if needed, these tasks can reenter the Angular zone via run.

constructor(private _ngZone: NgZone) {}
// Loop outside of the Angular zone
  // so the UI DOES NOT refresh after each setTimeout cycle
  processOutsideOfAngularZone() {
    this.label = 'outside';
    this.progress = 0;
    this._ngZone.runOutsideAngular(() => {
      this._increaseProgress(() => {
        // reenter the Angular zone and display done
        this._ngZone.run(() => { console.log('Outside Done!'); });
      });
    });
  }

14 September, 2022

Error: Module not found: Error: Can't resolve '@angular/localize/init' in Angular 14

Error:  

./src/polyfills.ts:59:0-32 - Error: Module not found: Error: Can't resolve '@angular/localize/init' in 'C:\source\repos\Project1\Project1\ClientApp\src'  

× Failed to compile.


How to Fix it?

This error occurred due to a missing package in the package.json file.

Installing the package and importing it into polyfills.ts are both required. Running is the fastest way to do this.

npm install @angular/localize --save


Finally, it works here is the result:





30 August, 2022

Angular Error: Schema validation failed with the following errors: Data path "" should NOT have additional properties(project)

 

Solutions:


When I was getting version error issues, the Following command worked for me:

First, run:

    npm update

Second run:

    ng update

Third run: (It will update all the mismatching packages)

    ng update --all --force


OR
Run this command which will  Perform a basic update to the current stable release of the core framework
 and CLI by running the following command.

ng update @angular/cli@^<major_version> @angular/core@^<major_version>

17 May, 2022

Angular-npm ERR cb() never called

 Angular-npm ERR cb() never called

Here is easy steps to solve this problem?

while installing a node package from the package.json file and the package-lock.json file is corrupted due to some reasons like  the node.js version is updated to the latest,  you may see an error like this in our terminal.

Following are the possible solutions to this problem, I trust, you may try one of them will work for you.

Solution 1:

npm config set registry https://registry.npmjs.org/

Solution 2:

npm cache clean

Or

npm cache clean --force

You might also manually remove the node_modules folder and try again in case the command above failed.

If still doesn't work, the global cache might be broken, try running npm cache clean --force and then do a clean install.

Solution 3:

npm install -g npm

Just globally installed the newest version of NPM and my guess Clearing npm cache is optional.



02 August, 2021

Angular 10: Can't bind to 'ngIf' since it isn't a known property of 'div'

 Error: Angular 10: Can't bind to 'ngIf' since it isn't a known property of 'div'

or

can't bind to 'ngif' since it isn't a known property of 'ng-container' angular 11


Solutions:

Make sure to import CommonModule from the module that is providing your component. for me I had to import CommonMudel in the TestComponent




import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
imports: [CommonModule],
declarations: [TestComponent]
})
class MyComponentModule {}


BrowserModule vs CommonModule

BrowserModule provides services that are essential to launch and run a browser app.


BrowserModule also re-exports CommonModule from @angular/common, which means that components in the AppModule module also have access to the Angular directives every app needs, such as NgIf and NgFor.


CommonModule (all the basics of Angular templating: bindings, *ngIf, *ngFor…), except in the first app module, because it’s already part of the BrowserModule

14 May, 2020

Angular 9 with Docker Step by Step example

Angular 9 with Docker Step by Step example

 

I had the plan to learn docker and use an angular app running under the docker environment. I was struggling to get the right and simple steps to start with. So I invested almost 2 days to learn basic docker and working with angular 9 and finally I was able to make it. Congrats to me!! 😊

Setting up the local environment and workspace

Prerequisites:

Angular Project Setup :

After installing the above tools open you CMD/Angular CLI 

installed Angular: If you are new to an angular good visit here learn and step  https://angular.io/guide/setup-local

Step 1: Install the Angular CLI

               npm install -g @angular/cli

Step 2: Create Hello World application

ng new hello-world

Step 3: Run the application

cd my-app

ng serve --open

 or Open your working folder(hello-world) in vs code and run ng serve --open

Great you are down with your angular project and your application is running now you can verify visiting over http://localhost:4200/ 

Docker Setup for your Hello-World Applications

 What is Docker?

·        Docker is a set of platforms as a service products,

·        Uses OS-level virtualization to deliver software in packages called containers.

·        Developed by: Docker, Inc.

·        and Written in: Go,

·        Initial release date: 20 March 2013

What can I use Docker for?

·        Fast, consistent delivery of your applications

·        Responsive deployment and scaling

·        Running more workloads on the same hardware

 you are new to Docker, then visiting the following docker official website https://www.docker.com/ to learn

Visuals Studio Code Setup:

Got VS Code >> Extensions >> Search “Docker” >> install one from Microsoft only

visual-studio-code-docker-extension

Step 4: under your project root directory create a file named DockerFile (Without any Extensions), you can also create docker file with help VS CODE Command Palette...

Step 5: paste the following code to your DockerFile:

        Get a docker file code and details from here: http://4cb.online/blogs/Angular-app-with-Docker-Step-by-Step-exampleile data from here:  

Note*: If you are facing any issue related to Nginx Just install with the following command

Npm install nginx

What is nginx?

NGINX is open-source software and provides a mechanism for web serving, reverse proxying, caching, load balancing, media streaming, etc. It started out as a web server designed for maximum performance and stability. In addition to its HTTP server capabilities, and load balancer for HTTP, TCP, and UDP servers.

Step 6: Build Image with VS Code

               Open your docker file created in Step 5

               Right Click(mouse) >> Build Image...

               Select your latest project:   "hellodocker:latest"

Step 7: RUN your image with the following command in terminal

               docker run --rm -it  -p 80:80/tcp hellodocker:latest

               or

               got to your image >> right click>> RUN

 

docker-run-vscode


You have done with your first docker app, by default it is running on port:80, http://localhost/

Finally, here we go with the angular running app

Push to Docker Hub 

As you know docker runs on images(can be called out stopped Containers), you push your hello-world image to docker hub for your future use or next-level learning.

·        Go to https://hub.docker.com/

·        Create your account

·        Note down your docker ID that will be used to push your images

·        To push your hello-world image

·        Open vs code >> right click on image>>push

·        It will ask for docker ID and password first provide it 

And all done 😊

 

docker hub



17 January, 2020

Angular 8 Azure Active Directory Authentication

Angular 8 App With Azure Active Directory Authentication


Today we are going to use the Active Directory Authentication Library (ADAL) for angular 8/JavaScript (ADAL.JS) that offers Azure AD authentication services that can be incorporated in the single-page applications(SPA).

if you are new to Angular 8 so ahead have a look into the first angular 8 projects and then go through the step by steps and instructions to implement authentication.

Step 1: Configuring Azure Active Directory (App Registrations)

  • Login to Azure Portal
  • Click on Azure Active Directory >> App Registrations >> New Registrations
  • Enter the display name
  • Select the supported account type(in my case Single Tenant App)
  • Enter the Redirect URI( default URL for the angular https://localhost:4200/)
  • Click on Register button

AAD-App registrations

  • Find newly created app under app registrations "angular-app-web-dev" and click on Authentication in left panel >> under Implicit grant >>  ID tokens tick the checkbox >> click on the Save Button
AAD App Registration - Authentication Settings


Get the following details from registered App that can be found under Overview sections
  • Client Id - (GUID)
  • Tenant Id - (GUID)
AAD - ClientId and TenantId


Step 2 - Angular Project Updates for ADAL

Open the angular app in vscode and open the terminal  

Install the microsoft-adal-angular6 npm package

Run the following command to install ADAL package and this package will be added to your dependencies section in package.json:

 npm i microsoft-adal-angular6 --save

Update environment.ts file with the following details

Just the end of step -1 we got the tenant id and client Id
    
    tenantId: 'c71b45bc-73d9-4208-95bb-1f5b7dd22cbf',  // replace with yours one here
    clientId: '73d9-4208-95bb-49cd-c71b45bc-73d9-4208', // replace with yours one here
    redirectUri: 'https://localhost:4200', // replace with the yours one here
    postLogoutRedirectUri: 'https://localhost:4200/logout', // replace with yours one here
    extraQueryParameter: 'nux=1' //(optional)
environment.ts

Update app-routing.module.ts  to secure individual route (your route modules)

Import the AuthenticationGuard  into your file

import { AuthenticationGuard } from 'microsoft-adal-angular6';

const routes: Routes = [
  { path: '', component: EmployeeComponent, canActivate: [AuthenticationGuard] } }
];

Update app.module.ts time with followings

Import the MsAdalAngular6Module, AuthenticationGuard into your file

import { MsAdalAngular6Module, AuthenticationGuard } from 'microsoft-adal-angular6';

add imports with the following configuration details

imports: [
    MsAdalAngular6Module.forRoot({
      tenant: environment.tenantId,
      clientId: environment.clientId,
      redirectUri: window.location.origin,
      // endpoints: environment.endpoints,
      navigateToLoginRequestUrl: false,
      extraQueryParameter: environment.extraQueryParameter,
      cacheLocation: 'sessionStorage'
    })
  ],

and also update the providers for the authentication gurad
  providers: [ 
    AuthenticationGuard
  ],

Display the Logged-in User Details

if you want to show the logged-in user details use the these properties


App-component.ts


this.adalSvc.LoggedInUserEmail // Get the Logged In User Email
this.adalSvc.LoggedInUserName // Get the Logged In User Name
this.adalSvc.logout() // Logs out the signed in user

You have done all the possible required steps, You do not have to call the login method it will be called implicitly.