<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[angularbr - Medium]]></title>
        <description><![CDATA[Esse espaço será destinado a artigos sobre Angular em português - Medium]]></description>
        <link>https://medium.com/angularbr?source=rss----766de4b71a25---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>angularbr - Medium</title>
            <link>https://medium.com/angularbr?source=rss----766de4b71a25---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 12 Nov 2026 21:05:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/angularbr" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Instalando Bootstrap ao nosso Projeto Angular]]></title>
            <link>https://medium.com/angularbr/instalando-bootstrap-ao-nosso-projeto-angular-511acbc7bfe9?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/511acbc7bfe9</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[bootstrap]]></category>
            <dc:creator><![CDATA[Alefbacelar]]></dc:creator>
            <pubDate>Tue, 13 Sep 2022 22:02:51 GMT</pubDate>
            <atom:updated>2022-11-10T13:30:32.758Z</atom:updated>
            <content:encoded><![CDATA[<p>#Parte3</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*7IO4AL_chbGX8QclB2nQag.png" /></figure><p>Olá pessoal! Tudo na paz?</p><p>Este artigo vai ser breve, vou ensinar como instalar o bootstrap de uma forma simples e rápida.</p><p>Primeiro vamos abrir o terminal do nosso <strong><em>VS Code</em></strong> no nosso projeto em Angular.</p><p>“Aos que ainda não sabem como iniciar um projeto em Angular, segue o link do artigo onde ensino: <a href="https://medium.com/@alefbacelar/criando-projeto-em-angular-8f2b7aca7bb7">https://medium.com/@alefbacelar/criando-projeto-em-angular-8f2b7aca7bb7</a>”.</p><p>Agora vamos digitar o comando abaixo no terminal:</p><pre><strong><em>npm install bootstrap --save</em></strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*mQZ-_K6iBCzDOWvfS4fWvg.png" /></figure><p>Agora no nosso<strong> styles.scss </strong>global:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*5Yu7qwB1rFiOXhXcVpUcOA.png" /></figure><p>vamos adicionar o seguinte import.</p><pre><a href="http://twitter.com/import"><strong>@import</strong></a><strong> &#39;~bootstrap/dist/css/bootstrap.min.css&#39;</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*x2R4zHH24Z0kAq_IVIGRYA.png" /></figure><p>E fácil assim você já pode utilizar o bootstrap. Agora vamos no site do bootstrap: <a href="https://getbootstrap.com/docs/5.2/customize/components/">https://getbootstrap.com/docs/5.2/customize/components/</a></p><p>Peguei um nav-bar:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LsiBlG1nrmP4sZ1gO2Fntw.png" /></figure><p>E uma table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmkYwQwGSXJv0-vRhx93ag.png" /></figure><p>Meu código HTML do home-component.html no link abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae259ecc3d98b82c6fa1648319eacc5c/href">https://medium.com/media/ae259ecc3d98b82c6fa1648319eacc5c/href</a></iframe><p>E meu SCSS do home-component.scss:</p><pre><em>.container</em> {</pre><pre>margem superior: 10%;</pre><pre>cor da borda: rgb(139, 139, 139);</pre><pre>estilo de borda: sólido;</pre><pre>raio da borda: 15px;</pre><pre>}</pre><pre>uma{</pre><pre>cor branca;</pre><pre>}</pre><p>Após as alterações vamos ver nossa tela de home:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Trp8QxcecnoXZHCcq-rlvw.png" /></figure><p>Prontinho, agora já temos uma estrutura preparada para começarmos um CRUD :)</p><p>Na próxima falaremos como simular uma API REST.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=511acbc7bfe9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/instalando-bootstrap-ao-nosso-projeto-angular-511acbc7bfe9">Instalando Bootstrap ao nosso Projeto Angular</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[Dica rápida] Docker + Angular variáveis de ambiente]]></title>
            <link>https://medium.com/angularbr/dica-r%C3%A1pida-docker-angular-vari%C3%A1veis-de-ambiente-38d14f527084?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/38d14f527084</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[environment]]></category>
            <category><![CDATA[variaveis-de-ambiente]]></category>
            <dc:creator><![CDATA[Thiago S. Adriano]]></dc:creator>
            <pubDate>Sat, 03 Sep 2022 14:10:54 GMT</pubDate>
            <atom:updated>2022-09-02T18:57:25.041Z</atom:updated>
            <content:encoded><![CDATA[<p>Veja nesse artigo como trabalhar com variáveis de ambiente em um projeto Angular com Docker</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*85HBQ0sicU7LjCSFYZVL3A.png" /><figcaption>Variáveis de ambiente no Angular com Docker</figcaption></figure><p>Dando continuidade à minha série de artigos rápidos, hoje demonstrarei como podemos trabalhar com variáveis de ambiente em um projeto Angular dockerizado.</p><p>Para pular a etapa de criação de um novo projeto, eu utilizarei a versão final do código que eu criei para este post rápido. Caso tenha interesse em clonar este repositório, seguinte o seu link no meu Github: <a href="https://github.com/programadriano/angular-docker-env">angular-docker-env</a>.</p><p>Este projeto foi desenvolvido com uma versão recente do Angular e adicionado/alterado alguns arquivos que demonstrarei nos próximos passos, para que possamos passar dados o Docker no momento de criação do nosso container e receber essas informações no Angular.</p><p>Com o projeto aberto no seu editor de preferência, vamos navegar pelo projeto. Os primeiros arquivos alterados foram os de ambiente, eu adicione uma propriedade chamada <strong>UrlImagem</strong> dentro deles:</p><pre><strong>environment.prod.ts</strong><br>export const environment = {<br>production: true,<br>UrlImagem:&#39;${URL_IMAGEM}&#39;<br>};</pre><pre><strong>environment.ts</strong><br>export const environment = { <br> production: false, <br>UrlImagem:&#39;https://br.web.img3.acsta.net/newsv7/20/02/03/22/01/2947023.jpg&#39;<br>};</pre><p>Em seguida foi injetado o valor da urlImagem no arquivo <strong><em>app.component.ts</em></strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd8b0ee307f9f4eaa27510e577432c8/href">https://medium.com/media/cfd8b0ee307f9f4eaa27510e577432c8/href</a></iframe><p>Por fim, foi adicionado dois arquivos no projeto, um Dockerfile e um outro chamado nginx.config para que possamos dockerizar o nosso projeto.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5d60f5d65ca64fe2e2f7a7b7d72d747/href">https://medium.com/media/b5d60f5d65ca64fe2e2f7a7b7d72d747/href</a></iframe><p>e o nginx.config:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2cbaad09f19dc16973bd131173250fd/href">https://medium.com/media/a2cbaad09f19dc16973bd131173250fd/href</a></iframe><p>Agora para testar este fluxo, vamos rodar o projeto para verificar se tudo está funcionando corretamente. Primeiro vamos executar ele local (ambiente de dev) com o comando ng serve --open , depois rodar ele dentro de um container Docker.</p><p>Assim que o comando ng serve --open finalizar ele vai abrir o projeto no navegador, e caso tudo esteja funcionando corretamente, você deve ter o seguinte resultado no seu navegador:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UlAuuvX8rKZ0ITb5Q8WNdg.png" /></figure><p>Agora para verificar o ambiente com o Docker, execute os seguintes passos:</p><pre><strong>Criação da nossa imagem:<br></strong>docker build -t angular-docker-env . </pre><pre><strong>Criação do nosso container passando a URL através do Env do Docker<br></strong>docker run -d -p 3090:80 --env URL_IMAGEM=&#39;https://th.bing.com/th/id/R.ee80696d91a77436c3dcef705777437d?rik=jFxlZAHJvPiC3g&amp;pid=ImgRaw&amp;r=0&#39; angular-docker-env</pre><p>Assim que o container for criado, abra no seu navegador o seguinte endereço: localhost:3090 e caso tudo esteja funcionando corretamente, você deve ver a seguinte imagem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EExxfvozcI4NXnVzrHQpFg.png" /></figure><p>Bom era isso que eu queria passar para vocês, espero que tenham gostado e até um próximo artigo pessoal ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38d14f527084" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/dica-r%C3%A1pida-docker-angular-vari%C3%A1veis-de-ambiente-38d14f527084">[Dica rápida] Docker + Angular variáveis de ambiente</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Directives — #3]]></title>
            <link>https://medium.com/angularbr/angular-directives-3-b39ba5c812df?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/b39ba5c812df</guid>
            <category><![CDATA[angular-directive]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Rafael Neves]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 14:44:06 GMT</pubDate>
            <atom:updated>2022-08-20T14:44:06.097Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Directives — #3</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*y7mFrad0MZX_sEWt.png" /></figure><p>Hey folks,</p><p>Let&#39;s talk in this chapter about Angular Directives.</p><h4>Introduction</h4><p>Directives are like markers on DOM element that communicate to Angular to include a specific behavior.<br>There three types of directives on Angular:</p><p><strong>Attributes directives</strong>: Change the appearance or the behavior of an element, component or another directive, as ngClass and ngStyle;</p><p><strong>Structural directives</strong>: Modify the layout adding or removing DOM elements, as ngIf and ngFor;</p><p><strong>Components</strong>: Are directives with a model</p><p>Starting the app on your terminal:</p><pre>ng new diretivasPoc</pre><p>Let&#39;s create a app that we can know a bit the directives that we will talk on this article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*_MAT2EP3QCmjMWtYmrorlA.png" /></figure><h4>Begin with <strong>ngIf:</strong></h4><p>It is a directive that allow us to change a page from a conditional declaration and that supposed to mean that put a ngIf in an element or component we can create or remove this element in the condition we provide:</p><p>To sum up convert a furnished value to an equivalent to <strong><em>true</em></strong> or <strong>false</strong>…after decides if show or not the element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*DXpFQjQR1bzbN5ox5ATBkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*2cGCURBMRt2LL5KNdqVmfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*8HzHIKW9yfvfG_iiaYA3Rw.gif" /></figure><h4><strong>ngSwitch</strong></h4><p>It is a directive that show an element of a group in basis of a condition. It uses the directives <strong>ngSwitchCase</strong> and <strong>ngSwitchDefault:</strong></p><p>Set a variable and uses in .html and setup below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/1*6j43dfaecHg_Eyvit644ag.png" /><figcaption>ngswitch.compoent.ts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*q1zJmMMIoGKthxyh5JhCrQ.png" /><figcaption>ngswitch.compoent.html</figcaption></figure><p>The result will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*fB-2r8JtqzcG0EUpkylGgQ.gif" /><figcaption>http:localhost:4200</figcaption></figure><h4><strong>ngFor</strong></h4><p>Do you know when we view a table list with a lot of information?<br>This happens with the help with a repetition loop that create all data one by one…<br>So the <strong>ngFor </strong>is a right tool to have on your sleeve.<br>How use the tool?</p><p>As below, we have a list to iterate:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*re3cN2GOH0ltpAXx4nzjHA.png" /><figcaption>ngfor.component.ts</figcaption></figure><p>We can present the data as a list or in a table list:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*cBOS4ku_NBXb0p3XUudfJg.png" /><figcaption>ngfor.component.html</figcaption></figure><p>Look how we see this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*1QA9kRQYLObXwCgWE-h0Ag.png" /><figcaption>http:localhost:4200</figcaption></figure><h4><strong>ngClass</strong></h4><p>It is a directive that allows you define a class dynamically from Dom element.<br>Let&#39;s on real how works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*R_M4BxLpHnwjNNYSfFW6sw.png" /><figcaption>ngclass.component.ts</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*0OirolglzFE0kpb1-7W3sw.png" /><figcaption>ngclass.component.html</figcaption></figure><p>Note that if !<strong>isFavorite </strong>show the icon (bi-star), else <strong>isFavorite</strong> (bi-star-fill)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*VUX54BbCRTu22_lvDAIPrQ.gif" /><figcaption>http://localhost:4200</figcaption></figure><h4><strong>ngStyle</strong></h4><p>It is used to add style in DOM element, look bellow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*dEsUaY7AqA1QeaxB7q5lYQ.png" /><figcaption>ngstyle.component.ts</figcaption></figure><p>On this example, I was far away using Inputs two way data binding to change the color font and size:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*wCyXfQyrBmucj-AuRf3wDA.png" /><figcaption>ngstyle.component.html</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*qpE9uPTe52cDOnqWMcRAZw.gif" /><figcaption>http://localhost4200</figcaption></figure><p>And this is it guys, this is a resume of how works with this basics directives. Considerer that we have too custom directives that allows you to create your own rules.<br>Take a look on my <a href="https://github.com/RafaelNevesdeOliveira/diretivasPoc"><strong>Github</strong></a><strong> </strong>on this repo.</p><p>See you all on the next….byeee</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b39ba5c812df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-directives-3-b39ba5c812df">Angular Directives — #3</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Service (GET) — #2]]></title>
            <link>https://medium.com/angularbr/angular-service-287e4086ee2d?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/287e4086ee2d</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[brazil]]></category>
            <category><![CDATA[carreer]]></category>
            <dc:creator><![CDATA[Rafael Neves]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 14:44:03 GMT</pubDate>
            <atom:updated>2022-09-14T02:14:11.986Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rrdBXmxlTqpm3xaE.png" /></figure><p>Hey folks,</p><p>Let`s talk in this chapter about Angular Services.</p><h3>Introduction</h3><p>Services in Angular are a medium to of communication between components.<br>The services are a great way to share data that doesn&#39;t know each other.<br>In this article we will build an app that will <strong>get</strong> a lot a of Digimon from an API-Rest.</p><p>Starting the app on your terminal:</p><pre>ng new servicePoc</pre><p>Once your repo was created, let&#39;s create a service class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*MuHMa6Ww3tlUmqr90_4HQg.png" /></figure><p>Something like this will be presented:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*06wwGj524gmVAlnHV658yQ.png" /><figcaption>service.service.ts</figcaption></figure><p>Adding httpClient, injectin on the constructor as private httt: HttpClient.</p><blockquote>HttpClient is a npm Angular package for making API calls over the backend server, to communicate frontend and backend and present a dynamic web app.</blockquote><h3>Injecting a Service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*SiLG3DAXwmMSBDRhoQSJpg.png" /><figcaption>service.service.</figcaption></figure><p>Right now our project will have that face config.</p><p>Do not forget to import the HttpClientModule on app.module:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vyp4kkDWLek9RXRBxTzqdA.png" /><figcaption>app.module</figcaption></figure><p>Note that we created a method inside the service ( <strong><em>getDigimonList</em></strong>). To call achieve the data from our API, check the JSON on link bellow:</p><p><a href="https://digimon-api.vercel.app/api/digimon">https://digimon-api.vercel.app/api/digimon</a></p><p>In the link, note on service that was separated to link to the route this is because if we need to get another routes, will be easy to provide the maintenance.<br>How many routes we need, we can add like above ( personally I find it easier).</p><p>With this did, now we will inject this service on component and present the html.<br>We can inject a service in a component, as following below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*aC_GoA9wRp78cf8WfIwDeQ.png" /><figcaption>app.component.ts</figcaption></figure><p>In the constructor , we can inject Service and we have subscribe the getAll list method to get the data and use it. On this particular example we will obtain the lista data from the api. Do not forget of call the method on ngOnInit() to start the app and has the method on execution.</p><p>Follow below the Html where we will present the data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RJ6PzGs_bGLXa4IPI9aVlg.png" /><figcaption>app.component.html → we use bootstrap 5 on this project</figcaption></figure><p>The final is result will be something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5yxaTScBG-oLLwxO9PZLww.png" /></figure><h3>Conclusion</h3><p>— The structure of angular app, once that we use to not repeat the code more the one time, the service centralize our business logic.<br> — Can be easily injected by dependency injection.<br> — They are very useful to use in more the one component.</p><p>To sum up, they must have contain logic. They need to be completely apart from view schemes.</p><p>So, this is it guys.<br>To checkout the code, follow the link of repo on github:<br><a href="https://github.com/RafaelNevesdeOliveira/ServicePoc">https://github.com/RafaelNevesdeOliveira/ServicePoc</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=287e4086ee2d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-service-287e4086ee2d">Angular Service (GET) — #2</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular Pipes]]></title>
            <link>https://medium.com/angularbr/angular-pipes-ddffdbcb9e56?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/ddffdbcb9e56</guid>
            <category><![CDATA[angular-pipe]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Rafael Neves]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 14:43:58 GMT</pubDate>
            <atom:updated>2022-08-20T14:43:58.726Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular Pipes — #1</h3><p>Hello everyone,</p><p>With the encouragement of my mentor and great friend Thiago Adriano, I decided to start a series of articles about my journey of technological studies.<br>This week to start things off I will introduce Angular Pipes.</p><p>So let’s see what we can do…</p><p>What is Angular Pipe?</p><p>A brief introduction.</p><p>Pipes are used to transform, currency amounts, dates and a lot of data for display.<br>They are simple functions to use in template model to accept a enter value and return a transformed value.<br>It very useful because we can use in all application and declare just one time.</p><p>Angular provides integrated pipes about typical data, including locale transformations, follow some commom pipes:</p><p>Date: formate date according to local rules<br>Uppercase: transform text in upper case<br>Lowecase: transform text in lower case<br>Currency: transform a number to a currency string, according to local rules<br>Decimal: provide decimal point, according to local rules<br>Percent: transform number to percentage string</p><p>Follow ahead, let’s the two examples of custom pipes and how we can implement it.</p><p>Using Angular CLI.</p><pre>ng g new pipe-test</pre><pre>ng g c pipestest</pre><p>Create a folder to alocate your pipes and we have something like that?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/1*edsVfFpmIpdR3UPfPGgB2w.png" /></figure><p>Once we have created your files to present the pipes, let’s create two custom pipes:<br>1 — CPF and CNPJ</p><pre>ng g p cpf-cnpj</pre><p>I’ll not enter in details about Regex (Regular Expression), but as you can see below we use to replace characters equal to 11 to cpf and equal to 14 to cnpj, returning expressions with the correct expression.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*EmglUX261Q7s_GmOM08s-Q.png" /></figure><p>2 — Converting Fahrenheit temperature to Celsius or Celsius to Fahrenheit</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*4_7jzpQuEGNt4h4n-l3jHQ.png" /></figure><p>PS: Note that both pipes we have implemented PipeTransform ( it is a interface that is call by pipes to perform a transformation. Angular invokes that methos to binding the first value to any parameter to the second.</p><p>As result of this Pipes we have the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xsxqxaOPI3mxH2ptb8vFpg.png" /></figure><p>The #1, we have a regular pipe from angular, and about #2 and #3 Custom Pipes.<br>As you can note, on column of Raw Data is the raw data that we can input or receive from a API, and the Pipe Trnasform is the result treated by a pipe</p><p>Follow HTML to see how we call the pipes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AKrFiBt_8Qz2cg-8vii0Fg.png" /></figure><p>Do not forget to import the pipes on App.Module to use on HTML.</p><p>So this is it fellows, I will focus on post more articles about angular and another techs.</p><p>Until the next..byee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*HpefOHylur_guUQkZk7RhQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddffdbcb9e56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-pipes-ddffdbcb9e56">Angular Pipes</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Criando Projeto em Angular]]></title>
            <link>https://medium.com/angularbr/criando-projeto-em-angular-8f2b7aca7bb7?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/8f2b7aca7bb7</guid>
            <category><![CDATA[ng-serve]]></category>
            <category><![CDATA[localhost]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Alefbacelar]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 14:43:36 GMT</pubDate>
            <atom:updated>2022-08-20T14:43:36.748Z</atom:updated>
            <content:encoded><![CDATA[<p># PARTE 1</p><p>Olá pessoal, aqui veremos um passo a passo de como criar um projeto em Angular e como rodar o projeto no terminal usando o comando “ng serve”.</p><p>Vou partir do principio que todos já tenham sua maquina configurada com o Node JS e Angular CLI.</p><p>Vamos começar criando uma pasta e dando um nome para ela:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*5VOMdqFjk58R0QRsPxMB5Q.png" /></figure><p>Na sequencia iremos entrar na pasta recém criada e abrir o terminal a partir dela:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*pnU6kPcs2xlBW8sVvupA9g.png" /></figure><p>Dentro do terminal iremos digitar o seguinte comando “ng new projeto-angular”</p><p>Vai aparecer está mensagem abaixo e só digitar “y” e escolher a opção “SCSS”</p><p>Agora é só aguardar a instalação dos pacotes npm. Isso pode demorar alguns minutos.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FyZrYf-OhUXQoulkKyGM5Q.png" /></figure><p>Após a instalação dos pacotes, vamos digitar o seguinte comando no terminal: “code .” este comado irá abrir o VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ZUL-xlMxqd-wqiJDnJCuVg.png" /></figure><p>A estrutura do seu projeto vai estar dessa forma:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*pNPK5QdzeOZ05Sxak-7Cbw.png" /></figure><p>Agora precisaremos abrir o terminal do VS Code, e fazer o caminho entre as pastas até a pasta app: “cd .\projeto-angular\src\app’’</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*SYyTnhh9VepAmSVmrKG-0g.png" /></figure><p>Agora é só digitar o comando “ng serve” e aguardar a compilação.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*Zp1d3q7B4hGtXAgcW05CsQ.png" /></figure><p>Depois de concluída, irá aparecer um link no terminal e é só abri-lo.</p><p>Link: <a href="http://localhost:4200/">http://localhost:4200</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibMiWX_fVNzsMTlcZWZuhQ.png" /></figure><p>Essa será a tela que você vai ver:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1CCflUO2MtYQiqGIEi0Qdw.png" /></figure><p>Bom pessoal este foi um artigo bem simples e bem resumido. No próximo vou ensinar como criar um componente e organizar o projeto no qual daremos seguimento. :)</p><p>Link do vídeo: <a href="https://www.youtube.com/watch?v=JM0T_Bace1o">https://youtu.be/JM0T_Bace1o</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f2b7aca7bb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/criando-projeto-em-angular-8f2b7aca7bb7">Criando Projeto em Angular</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 7: novas funcionalidades]]></title>
            <link>https://medium.com/angularbr/angular-7-novas-funcionalidades-aed4f7edcb36?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/aed4f7edcb36</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[angular-7]]></category>
            <dc:creator><![CDATA[Thiago S. Adriano]]></dc:creator>
            <pubDate>Sun, 21 Oct 2018 04:18:48 GMT</pubDate>
            <atom:updated>2018-10-21T20:09:56.047Z</atom:updated>
            <content:encoded><![CDATA[<p>Veja nesse artigo como atualizar o seu ambiente de trabalho com a versão 7 do Angular e duas de suas novas funcionalidades</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iy4_AxlXzSDbjQWI.jpg" /><figcaption>Angular 7 novas funcionalidades</figcaption></figure><p>Já faz um bom tempo que eu estou focando os meus estudos no Angular, tive a oportunidade de participar de projetos com ele nas versões 2, 5 e 6. Hoje irei apresentar 2 novidades do que vieram nessa nova versão: o Drag and Drop e o Scrolling.</p><p>O primeiro passo será atualizar os nosso ambiente. Para isso, siga um dos passos abaixo de acordo com a versão que você tem instalada no seu computador:</p><p><strong>Versão &lt; 6</strong></p><pre>npm uninstall -g angular-cli<br>npm cache clean <br>npm install -g @angular/cli@latest</pre><p><strong>Versão 6</strong></p><pre>ng update @angular/cli @angular/core</pre><p>Para verificar se ele foi atualizado com sucesso, execute o comandong — versionno seu terminal. Abaixo você tem uma imagem demonstrando esse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*JDD_olvge-wR6ORvJr0TwQ.png" /><figcaption>Atualizando o Angular para versão 7</figcaption></figure><p>Para ficar um passo a passo legal, vamos criar um novo projeto. Para isso, abra um terminal no seu computador e execute o comando ng new, note que você irá receber uma mensagem perguntando qual e o nome do seu projeto.</p><p>Essa é uma das novidades dessa nova versão. Abaixo você tem uma imagem demonstrando esse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*V2pm_Wxnu9t9XrY8Sc7vEg.png" /><figcaption>Novo projeto Angular versão 7</figcaption></figure><p>Informe o nome do seu projeto, em seguida note que você irá receber uma outra mensagem perguntando se deseja adicionar um arquivo de rotas. Eu irei informar Y para que ele adicione.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*LHjBh5PFsgVDKbMjcUvspg.png" /><figcaption>Adicionando rotas no Angular 7</figcaption></figure><p>O próximo passo será informar como você deseja trabalha com os estilos no seu projeto. Eu irei selecionar SCSS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*GHrHpNokcZzZ-o-4XtDaPw.png" /></figure><p>Depois desse passo o seu projeto será criado. Para os próximos passos será necessário um editor de textos, eu irei utilizar o VS Code, mas você pode utilizar um de sua preferência.</p><p>Antes de nós começarmos a codar, vamos adicionar o Angular Material no nosso projeto. Para isso, execute o comando abaixo no seu terminal:</p><pre>ng add @angular/material</pre><p>Esse comando irá solicitar que você selecione um template para o seu projeto. Para esse artigo eu irei selecionar o indigo-pink.</p><p>Para as próximas perguntas eu irei informar <strong>N</strong> (não) para o HammerJS e <strong>Y</strong> (sim) para browser animations.</p><p>Com o projeto aberto no seu editor de textos, vamos conhecer as duas funcionalidades mencionadas no inicio desse artigo.</p><h4><strong>Drag and Drop</strong></h4><p>Nessa versão nós temos um módulo chamado DragDropModule. Para utilizar ele, basta adicionar a chamada abaixo no módulo que deseja utilizá-lo.</p><p>import {DragDropModule} from &#39;@angular/cdk/drag-drop&#39;;</p><p>Em seguida atualize o arquivo <strong><em>app.component.html</em></strong> com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b049944a9258dd4d82577e8a5a0e8871/href">https://medium.com/media/b049944a9258dd4d82577e8a5a0e8871/href</a></iframe><p>E o arquivo <strong><em>app.component.scss</em></strong> com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d0385e34dd8b0cd82e4b26563ab23be/href">https://medium.com/media/1d0385e34dd8b0cd82e4b26563ab23be/href</a></iframe><p>Abaixo você tem uma imagem demonstrando o resultado dessa implementação:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*h-2t8aBshT5z7X2_IKFKUw.gif" /><figcaption>Angular 7 drag and drop</figcaption></figure><h4>Scrolling</h4><p>Um outro módulo que chegou nessa nova versão foi o ScrollDispatchModule, ele nos permite trabalhar com <strong><em>virtual scroll.</em></strong></p><p>Para implementá-lo vamos criar um novo componente chamado VirtualScroll. Para isso, execute o comando abaixo no seu terminal:</p><pre><em>ng g c virtualScroll</em></pre><p>Em seguida atualize o seu arquivo <strong><em>app.component.html</em></strong> com o trecho de código abaixo:</p><pre>&lt;router-outlet&gt;&lt;/router-outlet&gt;</pre><p>E o novo componente no arquivo de rotas: <strong><em>app-routing.module.ts</em></strong>:</p><pre>{ path: ‘scroll’, component: VirtualScrollComponent }</pre><p>Agora para implementar o Virtual Scroll, vamos atualizar os arquivos: <strong><em>virtual-scroll.component.ts, virtual-scroll.component.scss e virtual-scroll.component.hml </em></strong>com os trechos de código abaixo:</p><p><strong><em>virtual-scroll.component.ts</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/550e255709b82277a61f4ce5d2e6002c/href">https://medium.com/media/550e255709b82277a61f4ce5d2e6002c/href</a></iframe><p>Analisando esse trecho de código nós temos:</p><ul><li>1: Estamos adicionando a chamada do ChangeDetectionStrategy para detectar as alterações no nosso componente</li><li>12: estamos criando um array com 100000 itens para passar para nossa view</li></ul><p><strong><em>virtual-scroll.component.hml</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07992974b396f2bfb3647f1d4036b310/href">https://medium.com/media/07992974b396f2bfb3647f1d4036b310/href</a></iframe><p><strong><em>virtual-scroll.component.scss</em></strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd9dcc43d7972a7fb762aa9c2acea7ee/href">https://medium.com/media/fd9dcc43d7972a7fb762aa9c2acea7ee/href</a></iframe><p>Abaixo você tem uma imagem demonstrando o resultado desse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*g-BcLQ2qc6ylFt4YPJRROA.gif" /><figcaption>Angular 7 Infinite Scroll</figcaption></figure><p>Os exemplos demonstrados nesse artigo foram retirados do site oficial do Angular. Caso tenham interesse em saber mais sobre essa nova versão, eu recomendo a leitura do seguinte link: <a href="https://angular.io/">Angular.io</a>.</p><p>Espero que tenham gostado e em bre ;)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed4f7edcb36" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-7-novas-funcionalidades-aed4f7edcb36">Angular 7: novas funcionalidades</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 6: CanDeactivate]]></title>
            <link>https://medium.com/angularbr/angular-6-candeactivate-923748d59481?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/923748d59481</guid>
            <category><![CDATA[desenvolvimento-software]]></category>
            <category><![CDATA[desenvolvimento]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[angular-6]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Thiago S. Adriano]]></dc:creator>
            <pubDate>Sun, 23 Sep 2018 18:00:58 GMT</pubDate>
            <atom:updated>2018-09-23T18:01:39.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0FeXlWnNgHLJdbjs.png" /><figcaption>Angular CanDeactivate</figcaption></figure><p>Dando continuidade aos meus artigos sobre Route Guards, hoje irei apresentar como utilizar o CanDeactivate.</p><p>Caso tenha interesse em ler os primeiros artigo, segue o link de cada um deles abaixo:</p><ul><li><a href="https://imasters.com.br/desenvolvimento/angular-6-route-guards">Angular 6: Route Guards</a></li><li><a href="https://imasters.com.br/desenvolvimento/angular-6-route-guards-parte-02">Angular 6: Route Guards — Parte 02</a></li></ul><p>O CanDeactivatedeve ser utilizado em cenários onde precisamos verificar se o usuário pode desativar um rota <strong>(ir para uma outra rota) </strong>ou não. Imagine o seguinte exemplo: O seu usuário está preenchendo um formulário e antes de salvar ele tenta ir para uma outra rota, com o canDeactivate você pode Interceptar e enviar uma mensagem para ele, solicitando que confirme se realmente deseja realizar essa operação.</p><p>Para os próximos passos eu irei utilizar o projeto iniciado no meu artigo anterior. Caso tenha interesse em clonar ele, segue o seu link no GitHub: <a href="https://github.com/programadriano/angular6-guards">Angular 6 Guards</a>.</p><p>Abra esse projeto no seu editor de textos, em seguida execute o comando abaixo no seu terminal:</p><pre>ng g s guards/productsdeactivate<br>ng g c products/product-edit</pre><p>O passo anterior deve criar um serviço chamado <em>ProductsdeactivateService</em> e um componente chamado <em>ProductEditComponent</em>. Adicione esse novo componente nas suas rotas, em seguida abra o arquivo <em>productsdeactivate.service.ts </em>e atualize ele com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61eeb96d1b2533a553cac7384557ef1a/href">https://medium.com/media/61eeb96d1b2533a553cac7384557ef1a/href</a></iframe><p><em>Não esqueça de adicionar esse serviço nos providers do seu ProductsModule.</em></p><pre>providers: [ProductsdeactivateService]</pre><p>Agora adicione o CandDeactivate na sua rota edit:</p><pre>{ path: &#39;product-edit/:id&#39;, component: ProductEditComponent, canDeactivate: [ProductsdeactivateService] },</pre><p>Em seguida atualize o arquivo <em>app.component.html</em> com o seguinte trecho de código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6fa51d2da725c4944fc41b7dad49024/href">https://medium.com/media/b6fa51d2da725c4944fc41b7dad49024/href</a></iframe><h4>Testando</h4><p>Para testar execute o comando <em>ng serve, </em>em seguida abra no seu navegador o endereço: <a href="http://localhost:4200/">http://localhost:4200/</a>. Abaixo você tem uma imagem demonstrando esse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uZ5JeeDKp2v0-03sl09M-w.gif" /><figcaption>(canDeactivate)</figcaption></figure><p>Bem simples né?</p><p>Dessa forma você consegue notificar o seu usuário antes que ele saia de uma determinada rota sem finalizar alguma ação necessária.</p><p>Bom, espero que tenham gostado e até um próximo artigo pessoal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=923748d59481" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-6-candeactivate-923748d59481">Angular 6: CanDeactivate</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 6: Route Guards]]></title>
            <link>https://medium.com/angularbr/angular-6-route-guards-3a621846b8e4?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/3a621846b8e4</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[desenvolvimento-software]]></category>
            <category><![CDATA[tecnologia]]></category>
            <category><![CDATA[angular-cli]]></category>
            <category><![CDATA[router]]></category>
            <dc:creator><![CDATA[Thiago S. Adriano]]></dc:creator>
            <pubDate>Wed, 15 Aug 2018 11:31:01 GMT</pubDate>
            <atom:updated>2018-08-15T11:31:01.540Z</atom:updated>
            <content:encoded><![CDATA[<p>Veja nesse artigo como proteger as suas rotas utilizando Router Guards</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*FoBYMXst87Ytw4LB" /><figcaption>Angular 6 (Router Guards)</figcaption></figure><p>No meu artigo anterior eu falei sobre <a href="https://imasters.com.br/front-end/angular-6-lazy-loading">Angular Lazy Loading</a>. Hoje irei demonstrar como proteger as nossas rotas utilizando o Route Guards.</p><p>Esse artigo será dividido em duas partes, nessa primeira irei apresentar duas formas de gerenciamento: <em>CanActivate </em>e o <em>CanActivateChild</em>. Para quem não conhece o Guard, em um breve resumo ele nos permite gerenciar a navegação das nossas rotas, abaixo irei criar alguns exemplos para que você possa entender ele melhor.</p><p>Existem quatro tipos diferentes de Guard:</p><ul><li><strong>CanActivate:</strong> válida se a rota está ativa</li><li><strong>CanActivateChild:</strong> válida se a rota filha está ativa</li><li><strong>CanDeactivate:</strong> verifica se uma rota pode ser desativada</li><li><strong>CanLoad: </strong>válida se um módulo está utilizando o lazily loading</li></ul><h4>Implementando Guards</h4><p>Para demonstrar a implementação do Guards eu irei utilizar um projeto desenvolvido no meu artigo anterior mencionado acima. Caso você tenha interesse em baixar ele, segue o seu link no GitHub:<a href="https://github.com/programadriano/angular-lazyloading"> Angular-lazyloading</a>.</p><p>O primeiro passo será criar uma interface. Para isso, abra um terminal no seu computador, navegue até o projeto clonado e em seguida execute o seguinte comando: <em>ng g s guards/AuthGuard.</em></p><p>Esse comando criará uma nova pasta dentro de <em>app </em>chamada <em>guards</em> com dois arquivos: <em>auth-guard.service.ts</em> e <em>auth-guard.service.spec.ts</em>. Abra o arquivo <em>auth-guard.service.ts</em> e atualize ele com o seguinte trecho de código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b26646003144694e9b5ec6ed0bc06d3/href">https://medium.com/media/7b26646003144694e9b5ec6ed0bc06d3/href</a></iframe><p>Conforme você pode ver na imagem abaixo, o método <em>canActivate </em>retorna um <em>boolean</em>, eu deixei seu retorno como false para que possamos proteger o HomeModule.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*UA34eXCm8Vtw-CpJGFaYwQ.png" /><figcaption>Angular (canActivate)</figcaption></figure><p>O próximo passo será adicionar o <em>AuthGuardService </em>nos <em>providers </em>do <strong><em>AppModule</em></strong>. Para isso, abra o seu arquivo: ./app/app.module.ts e adicione o trecho de código abaixo:</p><pre>providers: [AuthGuardService],</pre><h4>Testando o CanActivate</h4><p>Agora execute o comando <em>ng serve </em>no seu terminal, em seguida abra o endereço <a href="http://localhost:4200/">http://localhost:4200/</a> no seu navegador. Abaixo você tem uma imagem demonstrando o resultado desse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CVjmP2iqt-mL_Mw_eJHRrw.gif" /><figcaption>CanActivate</figcaption></figure><p>Como essa rota está protegida nós não conseguimos acessar o <em>HomeModule</em>. Agora altere o retorno da variável <em>isAuthenticated </em>em <em>AuthGuardService </em>para <strong>true </strong>e de um refresh na tela. Note que agora a rota está acessível.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPO6Q6KlfP5dIepJ7Uv9eg.gif" /><figcaption>CanActivate</figcaption></figure><h4>CanActivateChild</h4><p>Existem cenários onde precisaremos criar um módulo com componentes e esses componentes com filhos. Em projetos desenvolvidos com Angular nós podemos utilizar as rotas <strong>children</strong>.</p><p>Para ficar mais claro, vamos criar um novo módulo chamado produtos. Abra o seu terminal novamente e execute o comando abaixo:</p><pre>ng g m products --routing</pre><p>Esse comando irá criar um novo módulo chamado products. Vamos agora criar três novos componentes dentro dele:</p><pre>ng g c products/product-list<br>ng g c products/product-details<br>ng g c products/product-details/overview</pre><p>Agora abra o seu arquivo <em>products-routing.module.ts </em>e atualize ele com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8baf0f42c5d4677e55654fd29b2f1ed8/href">https://medium.com/media/8baf0f42c5d4677e55654fd29b2f1ed8/href</a></iframe><p>Em seguida adicione o <em>ProductsModule </em>em <em>app-routing.module.ts.</em></p><pre>{<br>  path: &#39;products&#39;,<br>  loadChildren: &#39;./products/products.module#ProductsModule&#39;<br>},</pre><p>O próximo passo será a criação de um serviço para implementarmos o <em>CanActivateChild</em>. Para isso, execute o comando abaixo no seu terminal:</p><pre>ng g s guards/AuthGuardChild</pre><p>Esse comando criará dois arquivos dentro do diretório <em>app/guards/.</em> Abra o <em>auth-guard-child.service.ts</em> e atualize ele com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f627458d51e32a0096ff647b6101cf7c/href">https://medium.com/media/f627458d51e32a0096ff647b6101cf7c/href</a></iframe><p>Analisando o código acima nós temos:</p><ul><li>08: implementando a interface <strong><em>CanActivateChild</em></strong></li><li>10: Criação de uma variável para simularmos um usuário logado</li><li>13: estamos recebendo um <strong>snap </strong>da rota ativada</li><li>14: estamos recebendo o estado da rota ativa</li></ul><p>Esse método deve retornar: Observable&lt;boolean&gt; | boolean</p><h4>Testando o CanActivateChild</h4><p>Agora execute o comando <em>ng serve</em> e abra o endereço <a href="http://localhost:4200/">http://localhost:4200/</a> no seu navegador: . Em seguida tente acessar as rotas abaixo:</p><pre><a href="http://localhost:4200/products">http://localhost:4200/products</a> <br><strong>(irá apresentar o conteúdo de list)<br></strong><a href="http://localhost:4200/products/product-details/13">http://localhost:4200/products/product-details/13</a><br><strong>(deve direcionar para home do projeto)</strong></pre><p>Abaixo você tem uma imagem demonstrando esse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_35X_YM9kd8PM7D2-cYlQ.gif" /><figcaption>(CanActivateChild)</figcaption></figure><p>Agora para liberar essa rota basta alterar o valor da variável <em>isAuthenticated</em> em <strong><em>auth-guard-child.service.ts</em></strong><em> </em>para <strong>true </strong><em>. </em>Abaixo você tem uma imagem demonstrando esse passo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6oYh381RCyaurirXOGv0Q.gif" /><figcaption>(CanActivateChild)</figcaption></figure><p>Agora para que possamos verificar o retorno dos parâmetros <strong>route</strong> e <strong>state </strong>atualize o arquivo <em>guard-child.service.ts </em>com o trecho de código abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a50a05465c29b264ed51358e7a71c11a/href">https://medium.com/media/a50a05465c29b264ed51358e7a71c11a/href</a></iframe><p>Em seguida abra a rota no seu navegador: <a href="http://localhost:4200/products/product-details/13">/products/product-details/13</a>. Para analisar os dados de retorno eu irei utilizar a ferramenta tools do <strong>Chrome</strong>. Abaixo você tem duas imagens demonstrando esses resultados.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*XC9-rDoioOfNFBdcPcCyDg.png" /><figcaption>CanActivateChild (ActivatedRouteSnapshot,RouterStateSnapshot)</figcaption></figure><p>Agora expandindo <em>ActivatedRouteSnapshot </em>nós temos os valores abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/742/1*amOHD03qVT3ZMJhOxzPt_Q.png" /></figure><p>Nós podemos trabalhar com esses dados dentro do método <strong><em>canActivateChild, </em></strong>basta você utilizar as duas variáveis criadas <strong>route </strong>e <strong>state</strong>.</p><p>Abaixo você tem um exemplo onde eu adicionei um console com o valor <em>console.log(route.params) </em>dentro do método canActivateChild.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*KiadqXtuukxwi183ZPFCjQ.png" /><figcaption>retorno console.log(route.params)</figcaption></figure><p>Bem simples né? Com isso finalizamos a primeira parte desse artigo sobre Guards, no próximo irei demonstrar o <strong>CanDeactivate </strong>e<strong> CanLoad. </strong>Espero que tenham gostado e até um próximo artigo pessoal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a621846b8e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/angular-6-route-guards-3a621846b8e4">Angular 6: Route Guards</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lodash com Angular 4]]></title>
            <link>https://medium.com/angularbr/lodash-com-angular-4-d1ccfb89123e?source=rss----766de4b71a25---4</link>
            <guid isPermaLink="false">https://medium.com/p/d1ccfb89123e</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[lodash]]></category>
            <dc:creator><![CDATA[Thiago S. Adriano]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 18:24:21 GMT</pubDate>
            <atom:updated>2017-10-03T16:31:32.803Z</atom:updated>
            <content:encoded><![CDATA[<p>Trabalhando com a biblioteca <strong><em>Lodash </em></strong>em uma aplicação Angular 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hcBUsls2mbg1nr8GRuqUmA.png" /></figure><p>Para esse artigo, nós iremos partir de um projeto já criado com o <strong><em>Angular Cli</em></strong>.</p><p>Nosso primeiro passo será a criação de um <strong><em>Service </em></strong>para que possamos receber os nossos dados. Para isso, execute o comando a baixo no seu terminal:</p><pre><strong>ng g s services/Person</strong></pre><p>A execução desse comando irá gerar dois novos arquivos <strong><em>.ts,</em></strong> dentro de um novo diretório chamado <strong><em>services </em></strong>na nosso <strong><em>Solution</em></strong>. Podemos ver esse passo na imagem a baixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*kiYnO_-s-xeo_-0HhEiH6w.png" /></figure><p>O arquivo <strong><em>person.service.spec.ts</em></strong> é criado para que possamos testar o nosso service, não iremos utilizar ele nesse artigo. Agora o arquivo <strong><em>person.service.ts</em></strong> será o responsável por receber os nossos dados externos e passar em forma de Injeção de Dependência para os nossos componentes.</p><p>Para que possamos utilizar o <strong>Lodash</strong>, nós iremos precisar de um objeto que retorne uma lista de dados, para esse exemplo nós iremos criar um <strong><em>mock </em></strong>de uma lista de pessoas. Para isso, adicione um novo arquivo chamado <strong><em>persons.json </em></strong>e adicione os dados a baixo nele:</p><pre><strong>[<br>{<br>&quot;id&quot;: 1,<br>&quot;name&quot;: &quot;Steve Jobs&quot;,<br>&quot;birthday&quot;: &quot;24/02/1955&quot;<br>},<br>{<br>&quot;id&quot;: 2,<br>&quot;name&quot;: &quot;Bill Gates&quot;,<br>&quot;birthday&quot;: &quot;28/10/1955&quot;<br>}<br>]</strong></pre><p>Nosso próximo passo será importação da nossa lista dentro do nosso arquivo <strong><em>person.service.ts</em></strong>. Para que possamos importar algum modulo ou arquivo no <strong>TypeScript</strong>, nós podemos utilizar o <strong><em>require</em> </strong>junto com o caminho do arquivo, mas antes de utilizarmos ele, nós precisamos adicionar uma referencia no nosso arquivo <strong><em>typings.d.ts.</em></strong></p><pre><strong>declare const require : any;</strong></pre><p>Agora abra o seu arquivo de serviço e adicione a seguinte linha de código nele:</p><pre><strong>const persons = require(‘./persons.json’)</strong></pre><p>Notem que para importar o nosso arquivo de mock, estamos utilizando o <strong><em>./persons.json</em></strong>, fizemos isso porque ele foi criado dentro da pasta services, mesmo caminho que nós criamos o nosso <strong>Service</strong>.</p><p>Agora vamos importar a biblioteca do <strong>Lodash </strong>para o nosso projeto. Para isso, execute o comando a baixo no seu terminal:</p><pre><strong>npm install --save lodash</strong></pre><p>Para quem não conhece o <strong><em>Lodash</em></strong>, ele é uma biblioteca que facilita muito o nosso trabalho com a manipulação de arrays, numbers, objects, strings, etc. Caso queira conhecer ele melhor segue o link da sua <a href="https://lodash.com/docs/4.17.4">Documentação</a>.</p><p>Vamos agora criar um método para que possamos listar os nossos dados. Para isso, abra o seu arquivo de service novamente e adicione o código a baixo nele:</p><pre>getAll() {<br>    let result = persons;<br>    return result;<br> }</pre><p>O método acima está bem simples, estamos criando uma variavel chamada <strong>result </strong>e passando para ela a nossa lista. Para que possamos testar ela, abra o seu arquivo <strong><em>app.component.ts </em></strong>e adicione o código a baixo dentro do seu construtor:</p><pre>constructor(public personService: PersonService) <br>{<br>      console.log(personService.getAll());<br>}</pre><p>Acima nós estamos injetando o nosso service no nosso app.component.ts, em seguida nós chamamos o método criado para trazer todos os nossos resultados e enviamos os valores para nossa console.</p><p>Vamos agora utilizar o <strong><em>Lodash </em></strong>para criarmos uma pesquisa que nós retorne um valor pelo Id da pessoa. Para isso, adicione o código a baixo dentro do seu Person service.</p><pre>getById(id: number) {<br>    let result = persons;</pre><pre>result = _.find(persons, (person) =&gt; {<br>      return person.id = id;<br>    })</pre><pre>return result;<br>  }</pre><p>Vamos entender o nosso código: nós estamos criando um método simples recebendo um id, em seguida nós declaramos uma variável e passamos o valor da nossa lista para ela. Por fim, nós utilizamos o método .find do Lodash para buscar um resultado pelo Id. Para que possamos testar, adicione a linha a baixo dentro do construtor do seu <strong><em>app.component.ts</em></strong>:</p><pre>console.log(personService.getAll());<br>console.log(personService.getById(1));</pre><p>Agora rode o projeto com o comando <strong><em>ng serve, </em></strong>caso todos os passos anteriores estejam OK, você irá ver os valores a baixo na console do seu navegador o retorno dos métodos getAll e getById:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QWUFTiMEaJikZqrABnN4pw.png" /></figure><p>Acima nós temos um exemplo simples de utilização do Lodash, podemos encontrar na documentação muitos outros exemplos que podem facilitar o desenvolvimento no nosso dia a dia.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1ccfb89123e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/angularbr/lodash-com-angular-4-d1ccfb89123e">Lodash com Angular 4</a> was originally published in <a href="https://medium.com/angularbr">angularbr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>