Mudanças entre as edições de "Angular"
| (32 revisões intermediárias por 2 usuários não estão sendo mostradas) | |||
| Linha 1: | Linha 1: | ||
= Angular NG Client = | = Angular NG Client = | ||
| + | =Instalar= | ||
| + | * NodeJS | ||
| + | * MPN | ||
| + | * npm install -g @angular/cli | ||
| + | |||
| + | =Atualizar o Angular= | ||
| + | Para saber a versão | ||
| + | ng version | ||
| + | Para atualizar | ||
| + | ng update @angular/cli @angular/core | ||
| + | |||
| + | Para ver se as dependências precisam ser atualizadas | ||
| + | ng update | ||
| + | |||
| + | Para testes | ||
| + | ng test | ||
| + | ng e2e | ||
| + | |||
==Criando projeto== | ==Criando projeto== | ||
ng new [project name] | ng new [project name] | ||
Cirar projeto com as rotas | Cirar projeto com as rotas | ||
| − | ng new [project name] --routing -- | + | ng new [project name] --routing --no-standalone --skip-tests |
* Componentes | * Componentes | ||
| Linha 11: | Linha 29: | ||
* Serviços | * Serviços | ||
* [[Angular:Módulos|Módulos]] | * [[Angular:Módulos|Módulos]] | ||
| + | |||
| + | ==Colocando em produção== | ||
| + | ng build | ||
| + | ng build --base-href=/algumacoisa/ | ||
| + | |||
| + | ==Module== | ||
| + | Criando módulo com rota | ||
| + | ng g m modulo --routing | ||
| + | |||
| + | ===Lazy-loading=== | ||
| + | Criando um método para chamar módulos por Lazy Load (Carga sob demanda - Acesso) | ||
| + | |||
| + | /* Dentro do Arquivo routing-module */ | ||
| + | import { RouterModule, Routes } from '@angular/router'; | ||
| + | |||
| + | const routes: Routes = [ | ||
| + | { path: '', component: MainComponent }, | ||
| + | { path: 'v/:id', component: VComponent }, | ||
| + | { path: 'proceedings', loadChildren: () => import('../120_proceddings/proceddings.module').then(m => m.ProceddingsModule)}, | ||
| + | ]; | ||
| + | |||
| + | /* Arquivo de módulo destino */ | ||
| + | const routes: Routes = [ | ||
| + | { path: '', component: MainJournalComponent, children: | ||
| + | [ | ||
| + | { path: '', component: ProceedingWelcomeComponent }, | ||
| + | { path: 'view/:id', component: ProceddingsViewComponent }, | ||
| + | ] | ||
| + | } ]; | ||
| + | |||
| + | ===Componentes de outros módulos=== | ||
| + | No arquivo module.ts | ||
| + | schemas: [CUSTOM_ELEMENTS_SCHEMA], | ||
| + | imports: [ | ||
| + | CommonModule, | ||
| + | ProceddingsRoutingModule, | ||
| + | '''ThemeModule''' | ||
| + | ] | ||
| + | |||
| + | No arquivo componente | ||
| + | <app-theme-navbar></app-theme-navbar> | ||
| + | <router-outlet></router-outlet> | ||
| + | <app-theme-footer></app-theme-footer> | ||
==Componentes== | ==Componentes== | ||
| Linha 33: | Linha 94: | ||
===Rotas TS=== | ===Rotas TS=== | ||
| − | constructor(private Router: Router) {} | + | '''constructor(private Router: Router) {}''' |
| − | + | Redireciona pagina dentro da programação | |
| − | |||
this.router.navigate(['home']); | this.router.navigate(['home']); | ||
| + | this.router.navigate(['/']) | ||
| + | |||
Com reload da Página | Com reload da Página | ||
this.router.navigateByUrl('/home'); | this.router.navigateByUrl('/home'); | ||
| Linha 68: | Linha 130: | ||
<span>{{nome}}</span> (HTML) | <span>{{nome}}</span> (HTML) | ||
public nome="Nome" (TS) | public nome="Nome" (TS) | ||
| + | |||
| + | ==LocalStorage== | ||
| + | ng generate service service/local-storage | ||
| + | Salvando dados no navegador | ||
| + | localStorage.setItem('name', 'Gabriel'); | ||
| + | |||
| + | let name = localStorage.getItem('name'); | ||
| + | alert(`Hello, ${ name }!`); //Hello, Gabriel! | ||
| + | |||
| + | localStorage.removeItem('name'); | ||
| + | |||
| + | localStorage.clear(); | ||
| + | |||
| + | ===local-storage.service.ts=== | ||
| + | import { Injectable } from '@angular/core'; | ||
| + | |||
| + | @Injectable({ | ||
| + | providedIn: 'root', | ||
| + | }) | ||
| + | export class LocalStorageService { | ||
| + | private storage: Storage; | ||
| + | constructor() { | ||
| + | this.storage = window.localStorage; | ||
| + | } | ||
| + | |||
| + | set(key: string, value: any): boolean { | ||
| + | if (this.storage) { | ||
| + | this.storage.setItem(key, JSON.stringify(value)); | ||
| + | return true; | ||
| + | } | ||
| + | return false; | ||
| + | } | ||
| + | |||
| + | get(key: string): any { | ||
| + | if (this.storage) { | ||
| + | return JSON.parse(<any>this.storage.getItem(key)); | ||
| + | } | ||
| + | return null; | ||
| + | } | ||
| + | |||
| + | remove(key: string): boolean { | ||
| + | if (this.storage) { | ||
| + | this.storage.removeItem(key); | ||
| + | return true; | ||
| + | } | ||
| + | return false; | ||
| + | } | ||
| + | |||
| + | clear(): boolean { | ||
| + | if (this.storage) { | ||
| + | this.storage.clear(); | ||
| + | return true; | ||
| + | } | ||
| + | return false; | ||
| + | } | ||
| + | } | ||
==Services== | ==Services== | ||
| Linha 74: | Linha 192: | ||
==Formulários== | ==Formulários== | ||
| + | * [[Angular:FormBuild]] | ||
* [[Angular:Formulários]] | * [[Angular:Formulários]] | ||
| + | * [[Angular:ReactiveForms]] | ||
* [[Angular:AutoComplete]] | * [[Angular:AutoComplete]] | ||
==Ciclo de Vida== | ==Ciclo de Vida== | ||
* [[Angular:Ciclo de Vida]] | * [[Angular:Ciclo de Vida]] | ||
| + | |||
| + | ==If and Loop== | ||
| + | ===For while=== | ||
| + | <li *ngFor="let item of sources);let i = index"> | ||
| + | <a class="link" [routerLink]="['/sources/view/' + i]" routerLinkActive="router-link-active"> | ||
| + | {{ item.jnl_name }} | ||
| + | <span *ngIf="item.jnl_collection=='JA'">(Revista)</span> | ||
| + | </a> | ||
| + | </li> | ||
| + | ===For while conditional=== | ||
| + | [li *ngFor="let item of collection(sources,'JA');let i = index"> | ||
| + | [a class="link" [routerLink]="['/sources/view/' + i]" routerLinkActive="router-link-active"> | ||
| + | {{ item.jnl_name }} | ||
| + | [span *ngIf="item.jnl_collection=='JA'">(Revista)</span> | ||
| + | [/a> | ||
| + | [/li> | ||
| + | No componente | ||
| + | |||
| + | collection(journal: any[],type: string=''): any { | ||
| + | return journal.filter(p => p.jnl_collection === type); | ||
| + | } | ||
==Cookie== | ==Cookie== | ||
npm install ngx-cookie-service | npm install ngx-cookie-service | ||
| + | No módulo de serviço | ||
| + | import { CookieService } from 'ngx-cookie-service'; | ||
| − | + | public ngOnInit(): void | |
| − | + | { | |
| − | + | /******************************************************************** */ | |
| − | + | public setLibrary(id: string) { | |
| − | + | this.CookieService.set('library', id); | |
| − | + | } | |
| − | + | ||
| + | public getLibrary() { | ||
| + | if (this.CookieService.check('library')) { | ||
| + | return this.CookieService.get('library'); | ||
| + | } else { | ||
| + | return 0 | ||
| + | } | ||
| + | } | ||
| + | } | ||
| + | |||
| + | ==Tradução Angular== | ||
| + | npm i @ngx-translate/core @ngx-translate/http-loader | ||
| + | |||
| + | Após adicionar esse pacote, é necessário importa-lo para nossa aplicação, colocando-o no app.module.ts, como demonstra o exemplo abaixo: | ||
| + | |||
| + | @NgModule({ | ||
| + | declarations: [ | ||
| + | AppComponent | ||
| + | ], | ||
| + | imports: [ | ||
| + | BrowserModule, | ||
| + | HttpClientModule, | ||
| + | TranslateModule.forRoot({ | ||
| + | loader: { | ||
| + | provide: TranslateLoader, | ||
| + | useFactory: HttpLoaderFactory, | ||
| + | deps: [HttpClient] | ||
| + | } | ||
| + | }) | ||
| + | ], | ||
| + | providers: [], | ||
| + | bootstrap: [AppComponent] | ||
| + | }) | ||
| + | export class AppModule { } | ||
| + | |||
| + | export function HttpLoaderFactory(http: HttpClient) { | ||
| + | return new TranslateHttpLoader(http); | ||
| + | } | ||
| − | + | [[https://lucasbsilva29.medium.com/angular-linguagem-din%C3%A2mica-i18n-l10n-80fef8c7369a]] | |
| − | |||
==Bootstrap Angular== | ==Bootstrap Angular== | ||
| Linha 117: | Linha 296: | ||
public date: Data = new Date(); | public date: Data = new Date(); | ||
| − | + | ====Array==== | |
| − | public list: Array<{ nome: string, idade: number}> = [ | + | public list: Array<{ nome: string, idade: number}> = [ |
{ nome: "Rene", idade: 53 }, | { nome: "Rene", idade: 53 }, | ||
{ nome: "Viviade", idade: 52 }, | { nome: "Viviade", idade: 52 }, | ||
| Linha 126: | Linha 305: | ||
Remove um item de uma array | Remove um item de uma array | ||
this.list.splice(id) | this.list.splice(id) | ||
| + | |||
| + | ====Array Sample==== | ||
| + | let dt: Array<any> | any = { | ||
| + | di: dataS, | ||
| + | df: dataF, | ||
| + | field: this.field_search, | ||
| + | }; | ||
| + | |||
| + | ==Criar Modulo== | ||
| + | ng g m NOME --routing | ||
===Funções=== | ===Funções=== | ||
| Linha 134: | Linha 323: | ||
==Produção== | ==Produção== | ||
===Gerando Build=== | ===Gerando Build=== | ||
| + | |||
| + | =Angular Material= | ||
| + | *[[https://material.angular.io/ https://material.angular.io/]] | ||
| + | Instalar: | ||
| + | ng add @angular/material | ||
Edição atual tal como às 22h35min de 3 de abril de 2025
Índice
- 1 Angular NG Client
- 2 Instalar
- 3 Atualizar o Angular
- 4 Angular Material
Angular NG Client
Instalar
- NodeJS
- MPN
- npm install -g @angular/cli
Atualizar o Angular
Para saber a versão
ng version
Para atualizar
ng update @angular/cli @angular/core
Para ver se as dependências precisam ser atualizadas
ng update
Para testes
ng test ng e2e
Criando projeto
ng new [project name]
Cirar projeto com as rotas
ng new [project name] --routing --no-standalone --skip-tests
Colocando em produção
ng build ng build --base-href=/algumacoisa/
==Module==
Criando módulo com rota
ng g m modulo --routing
Lazy-loading
Criando um método para chamar módulos por Lazy Load (Carga sob demanda - Acesso)
/* Dentro do Arquivo routing-module */ import { RouterModule, Routes } from '@angular/router';
const routes: Routes = [
{ path: , component: MainComponent },
{ path: 'v/:id', component: VComponent },
{ path: 'proceedings', loadChildren: () => import('../120_proceddings/proceddings.module').then(m => m.ProceddingsModule)},
];
/* Arquivo de módulo destino */
const routes: Routes = [
{ path: , component: MainJournalComponent, children:
[
{ path: , component: ProceedingWelcomeComponent },
{ path: 'view/:id', component: ProceddingsViewComponent },
]
} ];
Componentes de outros módulos
No arquivo module.ts
schemas: [CUSTOM_ELEMENTS_SCHEMA], imports: [ CommonModule, ProceddingsRoutingModule, ThemeModule ]
No arquivo componente
<app-theme-navbar></app-theme-navbar> <router-outlet></router-outlet> <app-theme-footer></app-theme-footer>
Componentes
Novo componente
ng g c [/modules/brapci/headers/head]
Route - Routas
ng generate module app-routing --flat --module=app
Rotas com ID
constructor(private ActivatedRoute: ActivatedRoute) {}
ngOnInit() {
this.ActivatedRoute.params.subscribe(
res=>console.log(res.id,res.name)
)
/*********** GET *********/
this.ActivatedRoute.queryParams.subscribe(
res=>console.log(res.id,res.name)
)
}
Rotas TS
constructor(private Router: Router) {}
Redireciona pagina dentro da programação
this.router.navigate(['home']); this.router.navigate(['/'])
Com reload da Página
this.router.navigateByUrl('/home');
Rotas Ativas
routerLinkActive
[a routerLink="['/home',1]" [routerLinkActive]="['class_active']" [routerLinkActiveOptions]="{exact: true}">Home 1[a]
routerLink
[a routerLink="['/home',1]">Home 1[a]
Nova Inteface
ng g interface /modules/interface/vocabulary
Data Binding
Interpolation (sem espaços)
{ { title } } (HTML)
public title: string="Título" (TS)
Property Binding
<button [disabled]="disableButton">Botão</button> (HTML) <img [src]="imageCapaURL"> (HTML) <img src="Predefinição:ImageCapaURL"> (HTML)
Event Binding
<button (click)="calc()">Calcular</button> (HTML)
<button (click)="calc($event)">Calcular</button> (HTML)
public calc(valor: MouseEvent) { (TS)
console.log(valor) }
Two-way binding
<input ngModel="nome"> (HTML) Predefinição:Nome (HTML) public nome="Nome" (TS)
LocalStorage
ng generate service service/local-storage
Salvando dados no navegador
localStorage.setItem('name', 'Gabriel');
let name = localStorage.getItem('name');
alert(`Hello, ${ name }!`); //Hello, Gabriel!
localStorage.removeItem('name');
localStorage.clear();
local-storage.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root',
})
export class LocalStorageService {
private storage: Storage;
constructor() {
this.storage = window.localStorage;
}
set(key: string, value: any): boolean {
if (this.storage) {
this.storage.setItem(key, JSON.stringify(value));
return true;
}
return false;
}
get(key: string): any {
if (this.storage) {
return JSON.parse(<any>this.storage.getItem(key));
}
return null;
}
remove(key: string): boolean {
if (this.storage) {
this.storage.removeItem(key);
return true;
}
return false;
}
clear(): boolean {
if (this.storage) {
this.storage.clear();
return true;
}
return false;
}
}
Services
ng g s data/isbn
- Incluir no app.component (Http)
Formulários
Ciclo de Vida
If and Loop
For while
For while conditional
[li *ngFor="let item of collection(sources,'JA');let i = index">
[a class="link" [routerLink]="['/sources/view/' + i]" routerLinkActive="router-link-active">
Predefinição:Item.jnl name
[span *ngIf="item.jnl_collection=='JA'">(Revista)
[/a>
[/li>
No componente
collection(journal: any[],type: string=): any {
return journal.filter(p => p.jnl_collection === type);
}
Cookie
npm install ngx-cookie-service
No módulo de serviço
import { CookieService } from 'ngx-cookie-service';
public ngOnInit(): void
{
/******************************************************************** */
public setLibrary(id: string) {
this.CookieService.set('library', id);
}
public getLibrary() {
if (this.CookieService.check('library')) {
return this.CookieService.get('library');
} else {
return 0
}
}
}
Tradução Angular
npm i @ngx-translate/core @ngx-translate/http-loader
Após adicionar esse pacote, é necessário importa-lo para nossa aplicação, colocando-o no app.module.ts, como demonstra o exemplo abaixo:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
[[1]]
Bootstrap Angular
ng add @ng-bootstrap/ng-bootstrap npm install bootstrap bootstrap-icons
/* Editar o arquivoi angular.json */ "styles": [ "node_modules/bootstrap/scss/bootstrap.scss", "node_modules/bootstrap-icons/font/bootstrap-icons.css", "src/styles.scss" ], "scripts": [ "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js" ]
npm install @ng-bootstrap/ng-bootstrap
Variáveis
public title:string = "Brapci";
public valor:number = 1;
public valido:boolean = true;
public position: { x: number, y: number } = { x: 0, y: 0 };
public date: Data = new Date();
Array
public list: Array<{ nome: string, idade: number}> = [
{ nome: "Rene", idade: 53 },
{ nome: "Viviade", idade: 52 },
];
Insere um tiem em uma array
this.list.push({nome: "Nome", idade: 31 });
Remove um item de uma array
this.list.splice(id)
Array Sample
let dt: Array<any> | any = {
di: dataS,
df: dataF,
field: this.field_search,
};
Criar Modulo
ng g m NOME --routing
Funções
Rodando servidor
ng s
Produção
Gerando Build
Angular Material
Instalar:
ng add @angular/material