Run Angular on CodeSandbox and StackBlitz

Overview

In real-world scenarios, it frequently occurs that we would like to share our code with someone in exchange for assistance. If we share a GitHub repository, they will need to set up the environment before they can assist us.

There are tools like Codesandbox and Stackblitz accessible that provide us with an immediate development environment and make it incredibly simple to operate and distribute projects through these platforms.

Scope

This post will teach us about online tools that we may use to access a development environment at any time. Codesandbox angular and Stackblitz and what are the different features they prove out of the box.

Introduction

CodeSandbox Angular and StackBlitz Angular are development environments which are available online. These platforms have many features which help the end-users a lot if they want to run their code remotely.

How to Create & Run an Angular Project in CodeSandbox?

  1. Go to the website: link

    create and run  Angular project in CodeSandbox

  2. Create an account, click on Sign In and sign in using any of your following social logins:

    create and run  Angular project in CodeSandbox 2

  3. Select CodeSandbox Angular template

    create and run  Angular project in CodeSandbox 3

create and run an Angular project in CodeSandbox 4

Add Angular Material

Go to the left sidebar and choose Add Dependency to add the Material dependencies.

Add the following dependencies:

@angular/CDK
@angular/material

Add Angular Material

Import Angular Material Modules

Create a folder shared under the app folder. In the shared folder, create a file named material.module.ts:

File: material.module.ts

import { NgModule } from "@angular/core";
import { MatToolbarModule } from "@angular/material/toolbar";
import { MatCardModule } from "@angular/material/card";
import { MatIconModule } from "@angular/material/icon";
//...
@NgModule({
    declarations: [],
    imports: [],
    exports: [
        MatToolbarModule,
        MatCardModule,
        MatIconModule,
       // ...
    ]
})
export class MaterialModule {}

Now let's import this module into our app.module.ts :

File: app.module.ts

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";

import { AppComponent } from "./app.component";
import { MaterialModule } from "./material.module";

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, MaterialModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Add Material Core Theme

Rename src/style.css to src/style.scss and update the angular-cli.json file

"styles": ["styles.scss"],

Update style. scss with the following theme

@import "~@angular/material/theming";
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single CSS file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat-core();
// Define the palettes for your theme using the Material Design palettes available in the palette.suss
// (imported above). For each palette, you can optionally specify a default, lighter, and darker
// hue. Available color palettes: https://material.io/design/color/
$app-primary: mat-palette($mat-green);
$app-accent: mat-palette($mat-pink, A200, A100, A400);
// The warn palette is optional (defaults to red).
$app-warn: mat-palette($mat-red);
// Create the theme object (a Sass map containing all palettes).
$app-theme: mat-dark-theme(
    $app-primary,
    $app-accent,
    $app-warn
);
// Include theme styles for the core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
@include angular-material-theme($app-theme);

Adding Material Icon

Add a link element to the index.html file so that you can access the icon fonts CDN.

<!doctype html>
<html lang="en">

<head>
	<meta charset="utf-8">
	<title>Angular</title>
	<base href="/">
	<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"/>
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>

<body>
	<app-root></app-root>
</body>

</html>

Create the Landing Page

Update your app.component.html

<mat-toolbar color="primary">
    <mat-icon aria-hidden="false">eco</mat-icon>
</mat-toolbar>
<mat-card class="example-card margin-top-bottom-10">
    <mat-card-header>
        <mat-card-title>Title</mat-card-title>
        <mat-card-subtitle>Sub Title</mat-card-subtitle>
    </mat-card-header>
    <img mat-card-image src="./assets/cover.jpg" alt="Cover">
    <mat-card-content>
        <p class="justify">
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at mauris..
        </p>
    </mat-card-content>
</mat-card>

Under the src/assets folder, save the following picture as cover.jpg :

Creating the landing page

Creating Your First Template

Click on Sandbox Info from the CodeSandbox left menu, followed by Create Template.

You may now change the Template's name, description, colour, and icon.

When you create a new Sandbox in CodeSandbox angular, your template will be displayed.

Creating your first Template

By utilizing this template each time you develop a new application, you may now reduce the time it takes to integrate Material in Angular.

How to Create & Run Angular Project in StackBlitz?

  1. Go to the website:link

    create and run Angular project in StackBlitz

  2. Login using your GitHub account

  3. Create a new Angular project

    create and run Angular project in StackBlitz 2

Boom!!! It's done

create and run Angular project in StackBlitz 3

Yes, it is that easy, and with only three actions, we are prepared to begin.

Start your GitHub Project in Stackblitz

Our GitHub repository runs incredibly easily on StackBlitz Angular, thanks to StackBlitz.

  1. Copy the GitHub repo link https://github.com/srashtisj/angular-demo-app

  2. replace github.com to stackblitz.com/github

https://stackblitz.com/github/srashtisj/angular-demo-app

And done! Here's my GitHub repo on StackBlitz Angular:

Start your GitHub project in stackblitz

We can run and do whatever changes are required and then push the changes back to the repo.

Run Our Unit Tests in Stackblitz

We can indeed use StackBlitz Angular to execute our unit tests. A few adjustments must be made before we can run unit tests.

Note ­čĺíStackBlitz Angular just runs the main.ts file

Therefore, all unit test bootstrapping codes must be included in the main.ts file to begin Jasmine testing for your project in a StackBlitz. So let's create a new main.ts file and rename our current main.ts to main.ts.backup.

The next step is to use Jasmin from main.ts to execute our unit tests:

  1. initialize and import the modules for Jasmine and Jasmine for browsers.
  2. importing the zone.js module
  3. Import the the.spec.ts files.
  4. Angular test environment for Bootstrap

Import the following code into the main.ts file

import './polyfills';

// jasmine staff
declare var jasmine;
import jasmineRequire from 'jasmine-core/lib/jasmine-core/jasmine.js';
window['jasmineRequire'] = jasmineRequire;
import 'jasmine-core/lib/jasmine-core/jasmine-html.js';
import 'jasmine-core/lib/jasmine-core/boot.js';

// zone.js testing imports
import' zone.js/dist/zone-testing'; // instead all commented files below
//import' zone.js/dist/async-test';
//import' zone.js/dist/fake-async-test';
//import' zone.js/dist/long-stack-trace-zone';
// import 'zone.js/dist/proxy.js';
//import' zone.js/dist/sync-test';
//import' zone.js/dist/jasmine-patch';

// import testBed and Angular staff
import { getTestBed } from '@angular/core/testing';
import {
  BrowserDynamicTestingModule,
  platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';

// Spec files to include in the Stackblitz tests
import' ./app/app.component.spec.ts';


// get a fresh instance of jasmine and load the Angular test environment
bootstrap();

function bootstrap () {
  // I took it from Angular repo examples: 
  // https://github.com/angular/angular/blob/master/aio/content/examples/http/src/main-specs.ts#L25
  
  // this looks like a workaround to get a 100% fresh, clear run. 
  // window['jasmineRef'] does nothing - it is just a flag 
  // if it is not defined - we have a clear run
  // if not - let's reload
  if (window['jasmineRef']) { 
    location.reload();
    return;
  } else {
    window.onload(undefined); // overwritten by jasmine, initialize env
    window['jasmineRef'] = jasmine.getEnv();
  }

  // Initialize the Angular testing environment.
  getTestBed().initTestEnvironment(
    BrowserDynamicTestingModule,
    platformBrowserDynamicTesting()
  );
}

StackBlitz Example

Why Should I Run Angular Project Unit Tests in StackBlitz?

Occasionally we need to run unit tests for educational purposes or to make some playground links for use in technical publications. It's easier to use it.

Conclusion

  • CodeSandbox and StackBlitz are amazing tools for getting a development environment online
  • Creating a project on both platforms is super easy
  • Application Templates can be created on CodeSandbox to reuse in future
  • GitHub repository can be imported into stack blitz
  • Stackblitz angular also allows running unit tests on the platform
Free Courses by top Scaler instructors