Advertisement

#1 The Beginning of Our Forms Project

By the time we are done with this article we will have included the necessary packages for us to get up and running creating an angular application. We will also have created a razor page that will act as the starting point for our angular forms single page application. We will also have created the component that will contain the router outlet for the application and our first child component.

Project Creation

  • WebUi
    • package.json

Or course to start we need to create and setup a project. This will be the first article that we can make use of the three quick start guides that were just made. First off we need to start by actually creating the project using the asp.net core 2 quick start guide.. Once that is done we will turn to setting up css environment by using the scss quick start guide. And of course we are going to need to handle our typescript and scss files so we round out our set up using the quick start guide for webpack 4. Next as then name of this series implies we need to install angular in our project. In order to do this you can use either the npm install command (a) or copy the dependencies (b) into your package.json and use the npm install command. As you can see as of the writing of this article we are using angular 6.

npm install (1)

npm install --save-dev
@angular/common
@angular/compiler
@angular/core
@angular/forms
@angular/platform-browser
@angular/platform-browser-dynamic
@angular/router
core-js
rxjs
zone.js
(a) The npm install command that will install of the angular and related packages that we will need to begin our project.

package.json (1)

{
  ...,
  "devDependencies": {
    "@angular/common": "^6.0.3",
    "@angular/compiler": "^6.0.3",
    "@angular/core": "^6.0.3",
    "@angular/forms": "^6.0.3",
    "@angular/platform-browser": "^6.0.3",
    "@angular/platform-browser-dynamic": "^6.0.3",
    "@angular/router": "^6.0.3",
    ...
    "rxjs": "^6.2.0",
    ...
    "zone.js": "^0.8.26"
  }
}
(b) The relevant entries in our package.json file for the packages that we need to install.

Overview

Our general approach to projects within this series will be to create a razor page for the project that when we navigate to it the appropriate angular single page application (spa) we start up. For our forms project the general structure of our application will by necessity start with a module which will bootstrap a forms examples component which will contain our router outlet. From there any navigation will cause angular to construct and inject the appropriate component into our view. A simple schematic showing the relationship between the components is show in (c).

Image showing a the relationship between the 
             components in our project.
(c) Image showing a the relationship between the components in our project.

Our razor pages

  • WebUi
    • Pages
      • _SectionScripts.cshtml
      • Forms.cshtml
      • Index.cshtml

On each of the pages that we create we are going to need to include script tags that are particular for that page. In order to make that process easier we are going to start by creating a html partial (d). As you can see this partial just takes a single string argument at renders the appropriate script tag based on our environment. Next we need to modify our index page so that we make it easier to navigate to our forms page (e). And lastly we need to create our forms page which includes a base href that will be used by angular for routing and our form examples tag which will contain our router outlet as discussed previously.

_SectionScripts.cshtml

@model string

@{
    var developmentBundle = $"/js/{Model}.bundle.js";
    var productionBundle = $"/js/{Model}.bundle.min.js";
}

<environment names="Development">
    <script src="@developmentBundle"></script>
</environment>
<environment names="Staging,Production">
    <script src="@productionBundle" asp-append-version="true"></script>
</environment>
(f) An HTML partial page that will make it easier to conditionally include our script tags.

Forms.cshtml (1)

@page
@model FormsModel
@{
    ViewBag.Title = "Forms Demo";
}

@section Scripts {
    @Html.Partial("_SectionScripts", "forms")
}

<base href="/forms">
<form-examples></form-examples>
(g) The starting page for our forms application. This page contains a base href that the angular router will use to scope our route requests.

Index.cshtml (1)

@page
@model IndexModel
@{
    ViewBag.Title = "Index";
}

<nav>
    <a asp-page="forms">Forms</a>
</nav>
(e) Modifying out index page so that we have a link to the start of our forms application.

The basic component

  • WebUi
    • Source
      • forms
        • examples
          • basic
            • basic-example.component.pug
            • basic-example.component.scss
            • basic-example.component.ts

Since we need to import our components into our module definition we will start from the inside of (c) and work our way out. To start we will just create an essentially empty basic example component. We are just creating an h1 (h) and styling it (i) to make sure that our component (j) is created correctly.

basic-example.component.pug (1)

h1 basic
(h) The starting template for our basic example component.

basic-example.component.scss (1)

h1 {
    color: red;
}
(i) The starting styles for our basic example component.

basic-example.component.ts (1)

import { Component } from "@angular/core";

@Component({
    selector: "basic-example",
    template: require("./basic-example.component.pug"),
    styles: [require("./basic-example.component.scss")]
})
export class BasicExampleComponent { }
(j) The starting component definition for our basic example component.
Advertisement

The form examples component

  • WebUi
    • Source
      • forms
        • examples
          • form-examples.component.pug
          • form-examples.component.scss
          • form-examples.component.ts

Next we move on to our form examples component. As has been mentioned already this component will contain our router outlet (k) which again we are styling (l) to make sure everything is working correctly.

form-examples.component.pug (1)

nav.main-nav
    ul
        li
            a(routerLink="/basic", routerLinkActive="active-link") Basic

div.router-outlet
    router-outlet
(k) The template for our form examples component. The template contains both the links for navigation as well as the router outlet which will be the location that angular injects the components that are created in response to the use of the navigation links.

form-examples.component.scss (1)

.main-nav {
    background-color: lightblue;
}
(l) The starting styles for our form examples component.

form-examples.component.ts (1)

import { Component } from "@angular/core";

@Component({
    selector: "form-examples",
    template: require("./form-examples.component.pug"),
    styles: [require("./form-examples.component.scss")]
})
export class FormExamplesComponent { }
(m) The starting component definition for our form examples component.

The form examples module

  • WebUi
    • Source
      • forms
        • examples
          • form-examples.index.ts
          • form-examples.module.ts
      • main.site.ts

Now that our components are defined we can turn to creating our module. Before we do that though we will modify our main.site.ts file so that it contains a reference to zone.js which angular requires (n). Next to make our lives easier will create an index file that we can use to re-export all of our example components so that we can import from one file within our module (o). With all of that done we are now ready to create our form examples module (p).

main.site.ts (1)

import "zone.js/dist/zone";
if (process.env.ENV !== "production") {
    Error["stackTraceLimit"] = Infinity;
    require("zone.js/dist/long-stack-trace-zone");
}
(n) We need to include zone.js in our project for angular to work.

form-examples.index.ts (1)

export * from "./form-examples.component";
export * from "./basic/basic-example.component";
(o) By using an index file that exports the contents of our example components we only need to reference one form in our module definition.

form-examples.module.ts (1)

if (typeof module.hot !== "undefined") {
    module.hot.accept();
}

import { NgModule } from "@angular/core";
import { ReactiveFormsModule } from "@angular/forms";
import { BrowserModule } from "@angular/platform-browser";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";
import { RouterModule, Routes } from "@angular/router";

import {
    BasicExampleComponent, FormExamplesComponent
} from "./form-examples.index";

const routes: Routes = [
    {
        path: "",
        redirectTo: "basic",
        pathMatch: "full"
    },
    {
        path: "basic",
        component: BasicExampleComponent
    }
];

@NgModule({
    bootstrap: [
        FormExamplesComponent 
    ],
    declarations: [
        BasicExampleComponent,
        FormExamplesComponent
    ],
    exports: [
        RouterModule
    ],
    imports: [
        BrowserModule,
        ReactiveFormsModule,
        RouterModule.forRoot(routes, { useHash: true })
    ]
})
export class FormExamplesModule { }
platformBrowserDynamic().bootstrapModule(FormExamplesModule);
(p) The starting module definition for our form examples module.

A new entry point

  • WebUi
    • webpack.config.js

Now that everything is created we need to return to our webpack.config.js file and add an entry point for forms module (q).

webpack.config.js (1)

...
/*********************************
* Entry
*********************************/
const entry = {
    "forms": "./Source/forms/examples/form-examples.module.ts",
    "main": ["./Source/main.site.ts", "./Source/main.site.scss"]
}
...
(q) By adding a new entry point that references our form examples module we will include it in the creation of our bundles. It is important to note that the the key that we just added to our entry object, 'forms', is the same that is referenced in our forms razor page (g).

With that done we can rebuild our project and refresh the browser and we are now ready to get going creating our forms components. If all went well we should see output in our console that looks like (r) and the application should look something like (r).

Information displayed in the browser developer console showing our webpack
            configuration was correct.
(r) Information displayed in the browser developer console showing our webpack configuration was correct.
Image showing our angular application is building correctly and is up and running.
(r) Image showing our angular application is building correctly and is up and running.
Exciton Interactive LLC
Advertisement