Tag: Angular

Angular – Preview Image before Saving it

I came across a few samples of how to preview an image before saving it. So he’s my version “Angularfied”!

Here’s the app.component.ts (obviously move as you wish!)

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  // This is our callback to get the URL out of the onload function
  private  urlPointer: (name: string) => void;
 
  // Our temp url value
  url: string;
 
  /*
    loadFileTest triggered by (change)='loadFileTest($event)' in the html
  */
  loadFileTest(event) {
    this.getFileForPreview(event.target, this.urlPointer = (url) => this.setLocalURL(url));
  }
 
  /*
    getFileForPreview
    fileInput - event.target from the change event
    callbackFunction - pointer to our callback function (setLocalURL)
  */
  getFileForPreview(fileInput, callbackFunction) {
    const reader = new FileReader();
    reader.onload = function(){
      // setLocalURL with reader.result (a string)
      callbackFunction(reader.result);
    };
    // This is what actually creates our URL
    reader.readAsDataURL(fileInput.files[0]);
  }
 
  setLocalURL(url: string) {
    // Our call back function which gets the url and saves it to our url variable
    this.url = url;
  }
}

Then we just need to add the following HTML

<input type='file' accept='image/*' (change)='loadFileTest($event)'><br>
<img id='output' src='{{ url }}'>

As easy as that! ūüôā

Angular – Class initializers in TypeScript

One thing that is great in C# is the ability to¬†initialise values on create like so: –

MyObject test = new MyObject { Name="Test", Description="This is a description" };

With the release of TypeScript 2.1 you can now do something similar: –

export class MyObject{
    public Name: string;
    public Description: string;

    public constructor(
        fields?: {
            Name?: string,
            Description?: string
        }) {
        if (fields) Object.assign(this, fields);
    }
}

Then you can use is like so:-

new MyObject({ Name:"Test", Description="This is a description" });

Just make sure that in your package.json that devDependencies has typescript 2.1 or higher.

Why I love Angular

Having recently started at SSW (https://www.ssw.com.au) I had to learn Angular.  I had heard a bit about it however being firmly in the .Net space I had never learnt anything in detail.

I jumped online and found an course on Udemy by Mosh Hamedani (http://programmingwithmosh.com/) Angular 2 with TypeScript for Beginners: The Pragmatic Guide (https://www.udemy.com/angular-2-tutorial-for-beginners/) and started on my way. NOTE:- Use the Angular CLI for cleaner projects!

Below is a few reasons why I love Angular!

Components!

I found the setup and starting processes quite straight forward.  Angular is based on Components which allows us to break up our code into small chunks.  For example lets look at a basic page layout.

layout

We have 3 top level Components (Header, Content, and Footer) and then within Header we have two other components. Each component has its own HTML markup and can interact with the user in different ways.  We can create all of our pages as components that will be displayed in the content space making single page applications easy.

Once we are setup and running the main driver of our site is the app.component.ts file. This TypeScript file is the initial component rendered by our site by default and by adding in some Angular tags we can declare our components.

app-component

Above is the base component with our header, router-outlet (where our content goes), and our pagefooter.  Then we can create a header component and add in our children.

header-component

Now obviously we need to add in some CSS to control location however as you can see our components can be added easily by including a¬†tag (You also need to include them in your app.module.ts however that’s a discussion for a different day!) and we can then go to work on the individual components.

Without even trying using components has forced us to use the DRY (Don’t repeat yourself) and KISS (Keep it simple stupid) principals. ¬†You obviously could put all your code in one component however if you’re doing that you have bigger issues than worrying about principals! ¬†By using components we ensure reuse is simple to achieve.¬†An example would be¬†if you want to have a page showing cars for sale, create a car component and then repeat it for your data set!

Dependency Injection out of the box!

As someone who understands Dependency Injection but found it harder than it should have been I love how it is built into Angular.

So in Angular I need to use the http object when making service calls so its best if I just inject it. ¬†Here’s my code:-

injected

See what I did there? NOTHING!! I just called it in my constructor and set it to private so its accessible within my whole Component. ¬†I didn’t have to do anything else (although the http or other objects do need to be set to Injectable) and it just works! If you’ve been annoyed with Dependency Injection in the past¬†like me then I’m sure you understand how awesomely simple this is!

Separation of concerns

Ok this might actually be a cheat as any client framework has the same ability however I love it.  In the past I have always had issues with separation of concerns.  So many Developers put all their code into one Project which makes maintenance/deployments REALLY annoying.

With client side frameworks like Angular? You can’t do it. ¬†Your data context is firmly tucked away server side while your connection to it is done at the client. ¬†It¬†clearly separates the UI from the data layer forcibly.

In Summary

If you are a superstar developer you’re probably looking at the above thinking “Big deal I do that anyway” however that isn’t the point. ¬†In Development like anything in life you are only as strong as your weakest link. ¬†There is no point creating amazing code that only you can maintain, instead you want something maintainable by the whole team without you having to explain every detail to them.

That is why I love Angular, it forces even the weakest of coders to follow the basic principals of development which means better code and better applications. ¬†Yes there are a lot more technical reasons why it is awesome that I haven’t mentioned however whenever I look at frameworks I always want to know “How will it help me”¬†and Angular helps me by ensuring that I and my whole team follows the basic standards which while this should always be done sadly isn’t always the case!