Criar um aplicativo Angular

    Saiba como começar a criar um aplicativo Angular ao migrar do WPF para o Angular.

    Prerequisites

    Para começar a escrever Angular aplicativos, você precisa instalar o Node.js e o gerenciador de pacotes npm. Node.js é um ambiente de tempo de execução JavaScript que executa código JavaScript fora de um navegador. Para obter Node.js, vá para nodejs.org. O NPM é um gerenciador de pacotes semelhante ao gerenciador de pacotes NuGet para .NET. Ele é instalado com Node.js por padrão. Você também precisará de um IDE. Um dos melhores ambientes para desenvolver aplicativos Angular é o Visual Studio Code. É gratuito, de código aberto e funciona em todas as plataformas. Você pode obtê-lo com code.visualstudio.com.

    Create new project

    Se você é um desenvolvedor do WPF, criar novos projetos dentro do Visual Studio é bastante simples. Basta clicar em Arquivo -> Novo Projeto, selecionar o tipo de projeto, dar um nome a ele e pressionar OK. Como você está entrando no mundo Angular, deseja criar um novo projeto dentro do Visual Studio Code. No entanto, não há nenhuma nova opção de projeto aqui e isso ocorre porque o Visual Studio Code é baseado em arquivo e não em projeto. Para criar um novo aplicativo Angular, vamos usar o prompt de comando.

    Primeiro, você precisará instalar a Angular CLI.

    npm install -g @angular/cli
    

    Em seguida, navegue no prompt de comando até a pasta onde deseja que seu aplicativo seja criado e execute o seguinte comando:

    ng new demo-app
    

    Seremos solicitados "Gostaríamos de adicionar Angular roteamento?". Para esta demonstração, escolheremos NÃO. Em seguida, somos questionados sobre qual formato de folha de estilo gostaríamos de usar. Vamos ficar com o CSS básico por enquanto. Demora alguns minutos, mas eventualmente o processo será concluído e seu novo aplicativo será criado no disco.

    Agora temos que alterar os diretórios para a pasta demo-app que acabou de ser criada e executar um comando para abrir o Visual Studio Code.

    cd demo-app
    code .
    

    Isso iniciará uma nova instância do Visual Studio Code que contém seu aplicativo Angular. Agora, esta é provavelmente a parte que é provavelmente a mais esmagadora para os desenvolvedores de desktop que tentam aprender Angular- a estrutura de pastas.

    Project structure

    Vamos dar uma olhada em cada um desses arquivos e ver como eles se relacionam com um aplicativo WPF. A melhor maneira de fazer isso é comparar cada projeto lado a lado. À esquerda, temos nosso aplicativo WPF. À direita, temos nosso aplicativo 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.

    Infelizmente, aqui as semelhanças terminam. Vejamos alguns dos outros arquivos e pastas gerados:

    • 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

    Agora estamos prontos para executar o aplicativo, mas no Visual Studio Code você não pode simplesmente pressionar F5. Vamos abrir o Terminal do Visual Studio Code clicando no menu Terminal -> Novo Terminal ou pressionando Ctrl + Shift + `. Para executar o aplicativo, você deve executar o seguinte comando:

    ng serve
    

    Depois que o aplicativo for iniciado, você poderá abri-lo no navegador no seguinte URL http://localhost:4200/. Se você quiser que seu aplicativo seja aberto automaticamente no navegador, use o seguinte 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",
    

    Seu primeiro aplicativo Angular deve ter esta aparência:

    First Angular App

    Additional Resources

    Nossa comunidade é ativa e sempre acolhedora para novas ideias.