dir.by  
Поиск >>

Компьютер, программы
→
Angular
 Компоненты в Angular 
посмотрели 5753 раз
обновлено: 24 Augusta 2020
Компонента это представление.
Компонента отображается на экране в виде HTML элементов.
Example
  Файл app.component.ts
import { Component } from '@angular/core';

@Component({
     selector: 'my-app',
     template: `<label>Введите имя:</label>
          <input [(ngModel)]="name" placeholder="name">
          <h1>Добро пожаловать {{name}}!</h1>`
})
export class AppComponent {
     name: "";
}
Объяснение
Чтобы класс мог использоваться в других модулях, он определяется с ключевым словом export.
@Component
Декоратор @Component говорит что класс ниже это Angular компонента

  TypeScript  
@Component({
     selector: 'my-app',
     template: `<label>Введите имя:</label>
          <input [(ngModel)]="name" placeholder="name">
          <h1>Добро пожаловать {{name}}!</h1>`
})
export class AppComponent {
     name: "";
}


Декоратор @Component добавляет в класс AppComponent свойства: selector, template, ...

подробнее о декораторе класса в TypeScript ...

Декоратор @Component находится в библиотеке @angular/core поэтому мы импортируем
  TypeScript  
import { Component } from '@angular/core';
свойство template
Шаблон представляет кусок разметки HTML с вкраплениями кода Angular. Фактически шаблон это и есть представление, которое увидит пользователь при работе с приложением.

Шаблон может быть однострочным или многострочным. Если шаблон многострочный, то он заключается в косые кавычки (`), которые стоит отличать от стандартных ординарных кавычек (').

Каждый компонент должен иметь один шаблон.
свойство templateUrl
Можно вынести шаблон во внешний файл с разметкой html, а для его подключения использовать свойство templateUrl.

  TypeScript  
import { Component } from '@angular/core';

@Component({
     selector: 'my-app',
     templateUrl: './app.component.html'
})
export class AppComponent { }
свойство selector
  TypeScript  
selector: 'my-app'
template: `<label>Введите имя:</label>
     <input [(ngModel)]="name" placeholder="name">
     <h1>Добро пожаловать {{name}}!</h1>`


Соответственно html-страница с <my-app></my-app> будет заменена на template
  Html  
<label>Введите имя:</label>
<input [(ngModel)]="name" placeholder="name">
<h1>Добро пожаловать {{name}}!</h1>


Пример:
  Html  
<!DOCTYPE html>
<html>

<head>
     <meta charset="utf-8" />
     <title>Hello Angular 10</title>
</head>

<body>
     <my-app></my-app>
     <label>Введите имя:</label>
     <input [(ngModel)]="name" placeholder="name">
     <h1>Добро пожаловать {{name}}!</h1>
</body>

</html>
свойство styles
Для установки стилей в компоненте определено свойство styles:
  TypeScript  
@Component({
     selector: 'my-app',
     template: `<h1>Hello Angular 10</h1>
          <p>Angular 10 представляет модульную архитектуру приложения</p>`,
     styles: [`
          h1, h2{color:navy;}
          p{font-size:13px; font-family:Verdana;}
     `]
})
export class AppComponent { }


Селектор :host
Селектор :host ссылается на элемент, в котором хостится компонент. То есть в данном случае это элемент <my-app></my-app>. И селектор :host как раз позволяет применить стили к этому элементу

  TypeScript  
@Component({
     styles: [`
     h1, h2{color:navy;}
     p{font-size:13px;}
     :host {
          font-family: Verdana;
          color: #555;
     }
`]
свойство styleUrls
styleUrls позволяет указать набор файлов css, которые применяются для стилизации. В данном случае предполагается, что файл css располагается в проекте.

  TypeScript  
import { Component } from '@angular/core';

@Component({
     selector: 'my-app',
     template: `<h1>Hello Angular 10</h1>`,
     styleUrls: ['./app.component.css']
})
export class AppComponent { }
 
← Previous topic
Modules in Angular
 
Next topic →
Binding data in Angular
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
• What is Angular 8?
New Angular 8 application
Option 1. Creating a new Angular application from the console with the angular/cli command (50 files)
• Creating a new web application with Angular 8. Using the command line: npx -p @angular/cli@8.1.0 ng new
Option 2 (the best for me). Creating a new Angular application yourself (8 files)
• 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)
• What happens when I start an Angular 8 application? Run main.ts file. Creating a module.
Angular 9
• Creating a new web application with Angular 9 in Visual Studio Code. Use: Node.js + Angular (write our component in the ts file) + Typescript (convert ts files to js)
Angular 12
• Creating a new web application with Angular 12 in Visual Studio Code. Use: Node.js + Angular (write our component in the ts file) + Typescript (convert ts files to js)
• Adding routing (router) to the web application with Angular 12
Angular Description
• Modules in Angular
• Components in Angular
• Binding data in 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 for Angular
• Using Docker in a project with Angular (for Windows)
Angular Flex-Layout
• Angular Flex-Layout
WWW Sites to Learn Angular
• Sites to learn Angular

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