Creación de una aplicación Angular

    Obtenga información sobre cómo empezar a crear una aplicación Angular al migrar de WPF a Angular.

    Prerequisites

    Para comenzar a escribir Angular aplicaciones, debe instalar Node.js y el administrador de paquetes npm. Node.js es un entorno de tiempo de ejecución de JavaScript que ejecuta código JavaScript fuera de un navegador. Para obtener Node.js, vaya a nodejs.org. NPM es un administrador de paquetes similar al administrador de paquetes NuGet para .NET. Se instala con Node.js de forma predeterminada. También necesitará un IDE. Uno de los mejores entornos para desarrollar aplicaciones Angular es Visual Studio Code. Es gratuito, de código abierto y se ejecuta en todas las plataformas. Puedes obtenerlo de code.visualstudio.com.

    Create new project

    Si es un desarrollador de WPF, la creación de nuevos proyectos dentro de Visual Studio es bastante sencilla. Sólo tienes que hacer clic en Archivo -> Nuevo Proyecto, seleccionar el tipo de proyecto, darle un nombre y pulsar OK. Dado que va a entrar en el mundo Angular, desea crear un nuevo proyecto dentro de Visual Studio Code. Sin embargo, aquí no hay ninguna opción de proyecto nuevo y eso se debe a que Visual Studio Code está basado en archivos y no en proyectos. Para crear una nueva aplicación Angular, vamos a utilizar el símbolo del sistema.

    En primer lugar, deberá instalar la Angular CLI.

    npm install -g @angular/cli
    

    Luego navegue en el símbolo del sistema hasta la carpeta donde desea que se cree su aplicación y ejecute el siguiente comando:

    ng new demo-app
    

    Se nos preguntará "¿Nos gustaría agregar Angular enrutamiento?". Para esta demo elegiremos NO. A continuación, se nos pregunta qué formato de hoja de estilo nos gustaría utilizar. Vamos a quedarnos con el CSS básico por ahora. Tarda unos minutos, pero finalmente el proceso se completará y se creará la nueva aplicación en el disco.

    Ahora tenemos que cambiar los directorios a la carpeta de la aplicación de demostración que acabamos de crear y ejecutar un comando para abrir Visual Studio Code.

    cd demo-app
    code .
    

    Esto va a iniciar una nueva instancia de Visual Studio Code que contiene la aplicación Angular. Ahora bien, esta es la parte que probablemente sea más abrumadora para los desarrolladores de escritorio que intentan aprender Angular: la estructura de carpetas.

    Project structure

    Sigamos adelante y echemos un vistazo a cada uno de estos archivos y veamos cómo se relacionan con una aplicación WPF. La mejor manera de hacerlo es comparar cada proyecto uno al lado del otro. A la izquierda tenemos nuestra aplicación WPF. A la derecha tenemos nuestra aplicación Angular.

    WPF Project Structure Angular Project Structure

    It is important to keep in mind that an Angular application is a single page application (SPA) which means there is only one page in the entire app, and that is your index.html. The index.html file could be compared to the App.xaml of the WPF application. They are both global and everything you put there will show up on every single page of your application. The index.html file contains a section <app-root></app-root> which is similar to the StartupUri of the App.xaml file and specifies the first page we want to show when the app launches.

    What happens technically is when you navigate to the index.html, the main.ts JavaScript file invokes which loads the AppModule. An Angular application is made up of modules and components. By default, you get a root module and a root component and those are going to be located under the app folder. when the main.ts file invokes, we're going to bootstrap the AppModule, which is in the app.module.ts file in the app folder.

    The app module then bootstraps its own AppComponent. The AppComponent is defined in the app.component.ts file and its selector is set to app-root. The AppComponent has its html template defined in the app.component.html file. Basically the <app-root></app-root> section in the index.html page will visualize the content of the app.component.html file.

    The main.ts file is similar to the App.xaml.cs file since it is something like a code behind. The app.component.html, which is the default component shown when the application runs, is very similar to the MainWindow.xaml in WPF.

    In WPF we have a packages.config file which defines all our dependencies to nuget packages while Angular has a package.json file which contains the dependencies that your application requires to run. The package.json file contains also a section for scripts that you can run in the console when you are testing, starting or building your application.

    Let's take a look at the References folder. In WPF we have a References node in our solution that shows all the references that are added to this project. In an Angular application that is actually going to be the nodes_module folder. Coming from WPF, you may be surprised how many dependencies an Angular project has. These are populated by using npm.

    Desafortunadamente, aquí terminan las similitudes. Veamos algunos de los otros archivos y carpetas generados:

    • e2e - stands for end-to-end testing and contains integration tests or tests with real-world scenarios like a login process.
    • src - most of the application's code is located here.
    • assets - contains your images or any other assets.
    • environment - contains information about your build environments.
    • favicon.ico - the icon that appears in the browser when you are at your site.
    • karma.conf.js - contains configuration for the unit tests.
    • style.css - stylesheet with styles that are global for your application, it is similar to a resource dictionary defined in App.xaml in WPF.

    Run the application

    Ahora estamos listos para ejecutar la aplicación, pero en Visual Studio Code no puedes simplemente presionar F5. Vamos a abrir la Terminal de Visual Studio Code haciendo clic en el menú Terminal -> Nueva Terminal o presionando Ctrl + Shift + `. Para ejecutar la aplicación, debe ejecutar el siguiente comando:

    ng serve
    

    Una vez iniciada la aplicación, puede abrirla en el navegador en la siguiente URL http://localhost:4200/. Si desea que su aplicación se abra automáticamente en el navegador, debe usar el siguiente comando:

    ng serve -o
    

    In this case -o stands for open. Another way to start the application is by using the npm commands:

    npm start
    

    You could find those scripts defined in the package.json file and modify the start command by adding the -o option:

      "scripts": {
        "ng": "ng",
        "start": "ng serve -o",
    

    La primera aplicación Angular debería tener el siguiente aspecto:

    First Angular App

    Additional Resources

    Nuestra comunidad es activa y siempre da la bienvenida a nuevas ideas.