Transitioning from MVC to Angular 2 and TypeScript: A Step-by-Step Guide

Seeking guidance as I venture into the world of Angular. My goal is to pass a string variable 'element' to my UI and utilize it. However, I am unsure about how to go about passing it inside main.js and beyond. How can I transfer a variable to a typescript file from my MVC server? Index.cshtml:

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}

<app-root>Loading...</app-root>

In my layout file:

 @{
var elementServer = CamComponentGenerator.Api.App.elementID;
}

<!DOCTYPE html>
 <html>
 <head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - Cam Component Generator for Onshape</title>
<script src="~/node_modules/core-js/client/shim.min.js"></script>
<script src="~/node_modules/zone.js/dist/zone.js"></script>
<script src="~/node_modules/systemjs/dist/system.src.js"></script>
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/systemjs.config.js"></script>
<script>
    System.import('../ngapp/.compiled/main.js').catch(function (err)
    {
        console.error(err);
    });
</script>
<script>
    var element = "@elementServer";
</script>
  @Styles.Render("~/Content/css")
  @Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody()
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/Scripts/ccg-script.js")
@RenderSection("scripts", required: false)
</body>
</html>

In my main.ts file:

 import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
 import { AppModule } from './app.module';
 const platform = platformBrowserDynamic();
 platform.bootstrapModule(AppModule);

And in my app.ts file:

 import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { ParamsComponent } from './app/ccg-disk-cam-params/disk-cam-
 params.component';
import { CenterComponent } from './app/ccg-center/ccg-center.component';
import { ResultsComponent } from './app/ccg-results/ccg-results.component';
import { OutputComponent } from './app/ccg-output/ccg-output.component';
import { CylinderTranslatingComponent } from './app/ccg-disk-cam-follower-
params/cylinder-translating.component';
import { CylinderSwingingArmComponent } from './app/ccg-disk-cam-follower-
params/cylinder-swinging-arm.component';
import { SphereTranslatingComponent } from './app/ccg-disk-cam-follower-
params/sphere-translating.component';
import { SphereSwingingArmComponent } from './app/ccg-disk-cam-follower-
params/sphere-swinging-arm.component';
import { ModalComponent } from './app/ccg-modal/ccg-modal.component';
import { HttpModule } from '@angular/http';


@NgModule({
 imports: [BrowserModule, HttpModule, FormsModule ],
 declarations:
 [
    AppComponent,
    ParamsComponent,
    CenterComponent,
    ResultsComponent,
    OutputComponent,
    CylinderTranslatingComponent,
    CylinderSwingingArmComponent,
    SphereSwingingArmComponent,
    SphereTranslatingComponent,
    ModalComponent
],
 bootstrap: [AppComponent]
})
export class AppModule { }

Answer №1

To store a variable in JavaScript globally, you have two options: creating a global variable or utilizing local storage.

Global Variable:

Before initializing Angular:

<script>
        var element = "@elementServer";    
        var globalVariable = element;            
</script>

If you need to access the variable in your component, declare it as any:

declare var globalVariable: any;

Then you can use it like this:

var myGlobal = globalVariable;

Using LocalStorage:

This workaround involves passing the razor variable to JavaScript and saving it in localStorage for retrieval by Angular components.

It's important to note that these methods are not recommended for storing sensitive data.

So, before bootstrapping Angular 2:

<script>
    var element = "@elementServer";    
    localStorage.setItem('elementServer',element);
</script>

You can then retrieve the item in your Angular component:

var lstorage = localStorage.getItem("elementServer");

View Plunker Example

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

Repeatedly invoke http.post function and finally return the observable

In order to attach the list of documents, each document can contain a maximum of 20 MB data and the user has the ability to attach an unlimited number of files. Consequently, I am initiating one file upload per REST call. Upon successfully saving all the ...

What is the best way to mock imports in NestJS testing?

I am interested in writing a unit test for my nestjs 'Course' repository service, which has dependencies on Mongoose Model and Redis. courses.repository.ts: import { Injectable, HttpException, NotFoundException } from "@nestjs/common"; ...

Angular: facing difficulty displaying static html pages on server, although they render correctly when run locally

Within my Angular project, I have stored a few static html files (specifically sampleText.html) in the src/assets/html folder. In one of my components, I am attempting to fetch and display this file. The following code is being used for this purpose. Every ...

The Nrwl Nx administrative page located within the server instance

Hopefully my question is clear. We are working with a monorepo at nrwl that includes 2 applications, client and client-admin. I'm looking for the best way to deploy both of these applications on the same server but with different routes. Client-app ...

Utilizing Window function for local variable assignment

Currently, I am facing a challenge in my Angular2 service where I am attempting to integrate the LinkedIN javascript SDK provided by script linkedin. The functionality is working as expected for retrieving data from LinkedIN, however, I am encountering an ...

The button event listener in React fails to trigger without a page refresh

Within my index.html file, I have included the following code snippet: <head> ... <script type="text/javascript" src="https://mysrc.com/something.js&collectorId=f8n0soi9" </script> <script ...

When I apply both `*ngIf` and `*ngFor` to the same element, why does `*ngFor` insert a null item into the array that I am iterating over?

Custom Design, Visualization. Switching from the *ngIf directive to the [hidden] property greatly improves the appearance and eliminates any null items. ...

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

Sometimes encounter undefined values after assigning them through the service

One of the challenges I am facing is handling public fields in my service: @Injectable() export class ShareDataService { // Some code public templateForCurrencyCOS; public templateForPercentCOS; public templateForCurrencyCOGS; public te ...

Steps to initiate a PDF file download when a button is clicked using Angular 6

I need assistance with downloading the .pdf file when clicking a button. Below is the code I am currently using: downloadMyFile() { const link = document.createElement('a'); link.setAttribute('target', '_blank&apos ...

Do parallel awaits in JS/TS work only on Chrome browsers exclusively?

Encountering a strange issue with promise resolution behavior in JS/TS. Using Node LTS. It seems that the difference lies in whether the promise resolves to a value that is later read in the code or if it's simply fire-and-forget (void response type). ...

Unexpected issue with Ionic 4 subarray returning as undefined even though the index is accurate

When attempting to use console.log to view the value, I noticed that the value of noticeSet2[index] is undefined. However, when I print noticeSet, all the data in the array is displayed. Additionally, after printing the index using console.log, it correctl ...

Is there a way to assess Python code within a document's context using JavaScript in JupyterLab?

When using Jupyter Notebooks, I can create a cell with the following JavaScript code: %%javascript IPython.notebook.kernel.execute('x = 42') After executing this code, in another cell containing Python code, the variable x will be bound to 42 a ...

Tips for sending props, state, or arguments to a TypeScript React component

Hey there, total newbie here... I'm currently working on a school project and I've hit a bit of a roadblock... I'm attempting to pass some props from one component to another, but for some reason, it's not working properly. The goal ...

The Angular 2 function within the subscribe method is being triggered before the request has finished processing

I have been attempting to extract a parameter from a URL and then passing it to another method. Below is the code snippet: ngOnInit() { this.getParamValues(); } getParamValues() { this.route.queryParams.subscribe(params => { ...

Step-by-step guide on implementing Form.create in TypeScript and Ant Design with function components

Having trouble compiling my form created using Form.create(). The error message I'm getting is: Argument of type 'FunctionComponent<MyProps>' is not assignable to parameter of type 'ComponentType<{}>'. Type 'Fu ...

Angular6: Generating a dynamic list of radio buttons with unique identifiers

I have a challenge in creating a dynamic list of radio buttons from a JSON array. While I can successfully do that, the specific requirement is to assign a unique ID to each radio button generated. The structure of my JSON data is as follows: this.employe ...

Error encountered when an Angular expression is changed after it has already been checked in a dynamically generated component

I am encountering a problem with Angular and the CdkPortal/CdkPortalHost from @angular/cdk. I developed a service that allows me to associate a CdkPortalHost with a specified name and set its Component at any given time. This is how the service is struc ...

Combining types: unable to utilize the second optional type within a for loop

I am facing an issue while looping through an array due to the union type. I am wondering what I have overlooked in the code below that is causing Visual Studio Code to not recognize the second optional type for that specific array. class Menu { // name ...

Angular 2 Issue: @Input() Directive Not Recognized - Unresolved Reference Error

I am a beginner trying to grasp Angular2 concepts from ng-book 2(v49). Below is the code snippet from article.componenets.ts file: import { Component, OnInit } from '@angular/core'; import { Article } from './article.model'; @Componen ...