dir.by  
  Search  
Programming, development, testing
Angular
В web приложение с Angular 12 добавляем маршрутизацию (router)
  Looked at 2326 times    
 В web приложение с Angular 12 добавляем маршрутизацию (router) 
last updated: 7 Augusta 2021
Шаг 1. Создаем новое angular приложение
Шаг 2. Добавляем маршрутизацию в файл app.module.ts
  в файл app.module.ts добавляем
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }     from '@angular/forms';
import { AppComponent }     from './app.component';
import { PriceComponent }     from './price/price.component';
import { HomeComponent } from './home/home.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { APP_BASE_HREF } from '@angular/common';

const appRoutes: Routes = [
     { path: '', component: HomeComponent },
     { path: 'price', component: PriceComponent },
];


@NgModule({
     imports: [ BrowserModule, FormsModule, RouterModule.forRoot(appRoutes) ],
     declarations: [ AppComponent, PriceComponent, HomeComponent ],
     bootstrap: [ AppComponent ],
     providers: [{provide: APP_BASE_HREF, useValue: '/'}]
})
export class AppModule { }
Шаг 3. Добавляем маршрутизацию в файл app.component.html
  Html     в файл app.component.html добавляем
<h1>Добро пожаловать!</h1>

<img src="assets/arrow_right.png" (click)="myNavigate();" />

<router-outlet></router-outlet>
Шаг 4. Добавляем маршрутизацию в файл app.component.ts
  в файл app.component.ts добавляем
import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
     selector: 'app-root',
     templateUrl: './app.component.html',
     styleUrls: ['./app.component.scss']
})

export class AppComponent {

     myText1:string = "Hello!";

     constructor(private router: Router) {
     }

     ngOnInit(){
     }

     myNavigate()
     {
          this.router.navigate(['/price']);
     }

}
Шаг 5. Создаем PriceComponent
  Файл price.component.html
<h1>{{myText1}}!</h1>
  Файл price.component.scss
h1 {
     color: blue;
}
  Файл price.component.ts
import { Component } from '@angular/core';

@Component({
     selector: 'price',
     templateUrl: './price.component.html',
     styleUrls: ['./price.component.scss']
})

export class PriceComponent {

     myText1:string = "Book price!";

     constructor(){
     }

     ngOnInit(){
     }
}
Шаг 6. Создаем HomeComponent
  Файл home.component.html
<h1>{{myText1}}!</h1>
  Файл home.component.scss
h1 {
     color: yellow;
}
  Файл home.component.ts
import { Component } from '@angular/core';

@Component({
     selector: 'home',
     templateUrl: './home.component.html',
     styleUrls: ['./home.component.scss']
})

export class HomeComponent {

     myText1:string = "Home!";

     constructor(){
     }

     ngOnInit(){
     }
}
Важно
Содержимое HomeComponent и PriceComponent при навигации будет вставляться в <router-outlet></router-outlet> находящейся в файле app.component.html
Фотогалерея
Скачать пример
 
← Previous topic
Создаем новое web приложение с Angular 12 в Visual Studio Code. Используем: Node.js + Angular (пишем нашу компоненту в ts файле) + Typescript (конвертация файлов ts в js)
 
Next topic →
Модули в Angular
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
Что такое Angular 8?
Новое приложение Angular 8
Вариант 1. Создаем новое Angular приложение с консоли командой angular/cli (50 файлов)
Создаем новое web приложение с Angular 8. Используем командную строку: npx -p @angular/cli@8.1.0 ng new
Вариант 2 (для меня лучший). Создаем новое Angular приложение сами (8 файлов)
Create a new web application with Angular 8 in Visual Studio Code. We use: Node.js + Angular (write our component in ts file) + Typescript (convert files ts to js)
Что происходит при запуске Angular 8 приложения? Запуск main.ts файла. Создание модуля.
Angular 9
Создаем новое web приложение с Angular 9 в Visual Studio Code. Используем: Node.js + Angular (пишем нашу компоненту в ts файле) + Typescript (конвертация файлов ts в js)
Angular 12
Создаем новое web приложение с Angular 12 в Visual Studio Code. Используем: Node.js + Angular (пишем нашу компоненту в ts файле) + Typescript (конвертация файлов ts в js)
В web приложение с Angular 12 добавляем маршрутизацию (router)
Описание Angular
Модули в Angular
Компоненты в Angular
Привязка данных в Angular
Errors
Error "npm : The term 'npm' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spell included, verify that the path is correct and try again." | nodejs npm angular
Error "npm ERR! While resolving: @angular/flex-layout@12.0.0-beta.35 | Could not resolve dependency: | Conflicting peer dependency: @angular/cdk@12.2.13" | nodejs npm angular
ng serve Error "ng : The term 'ng' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spellin the path is correct and try again." | nodejs npm angular
ng serve Error "File ng.ps1 cannot be loaded. The file ng.ps1 is the current system." | nodejs npm angular
Error "Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js)" | nodejs npm angular
Docker для Angular
Используем Docker в проекте с Angular (под Windows)
Angular Flex-Layout
Angular Flex-Layout
WWW сайты для изучения Angular
Сайты для изучения Angular

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика