Angular 5 material для начинающих

Adding Data to your Material Table

For adding data to your table, you need to provide a data source. So first, open the file and add a array to the component:


We assume you have a that provides your application with data from a REST API back-end and a model that encapsulates an insurance policy type.

So, you simply need to get data from the back-end via this service and push it to your array. In the file, start by adding the following imports:

Next, you need to inject as a instance via the component’s constructor:

In the life-cycle event of your Angular component, call the method and subscribe to the returned Observable:

You simply assign the which contains the array of policies to your array. If you serve your project, you should see a table of data when you visit the address in your browser.

Angular Material Layout Components List

layout Components Example
Card <mat-card>Simple card</mat-card>
Divider <mat-divider></mat-divider>
Expansion Panel <mat-expansion-panel> <mat-expansion-panel-header> <mat-panel-title> Panel Title </mat-panel-title> <mat-panel-description> panel Description </mat-panel-description> </mat-expansion-panel-header> <p>I’m visible When opened</p> </mat-expansion-panel>
Grid list <mat-grid-list> <mat-grid-tile>1</mat-grid-tile> <mat-grid-tile>2</mat-grid-tile> </mat-grid-list>
List <mat-list role=»list»> <mat-list-item role=»listitem»>Item 1</mat-list-item> <mat-list-item role=»listitem»>Item 2</mat-list-item> </mat-list>
Stepper <mat-horizontal-stepper> <mat-step> Step 1 </mat-step> <mat-step> Step 2 </mat-step> <mat-step> Done </mat-step> </mat-horizontal-stepper>
Tabs <mat-tab-group> <mat-tab label=»First»> Tab 1 </mat-tab> <mat-tab label=»Second»> Tab 2 </mat-tab> <mat-tab label=»Third»> Tab 3 </mat-tab> </mat-tab-group>
Tree <mat-tree> <mat-tree-node> parent</mat-tree-node> <mat-tree-node> — child1 </mat-tree-node> <mat-tree-node> — child2 </mat-tree-node> </mat-tree>

CDN Based Version

You can include the angular-material.css and angular-material.js files into your HTML code directly from the Content Delivery Network (CDN). Google CDN provides content for the latest version.

We are using the Google CDN version of the library throughout this tutorial.

Example

Now let us rewrite the above example using angular-material.min.css and angular-material.min.js from Google CDN.

<html lang = "en" >
   <head>
      <link rel = "stylesheet"
         href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>

      <script type = "text/javascript">    
         angular.module('firstApplication', );
      </script>
   </head>
   
   <body ng-app = "firstApplication" ng-cloak>
      <md-toolbar class = "md-warn">
         <div class = "md-toolbar-tools">
            <h2 class = "md-flex">HTML 5</h2>
         </div>
      </md-toolbar>
      
      <md-content flex layout-padding>
         <p>HTML5 is the next major revision of the HTML standard superseding HTML 4.01,
         XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting 
         content on the World Wide Web.</p>

         <p>HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web
         ypertext Application Technology Working Group (WHATWG).</p>
         
         <p>The new standard incorporates features like video playback and drag-and-drop
         that have been previously dependent on third-party browser plug-ins such as Adobe
         Flash, Microsoft Silverlight, and Google Gears.</p>
      </md-content>
   </body>
</html>

The above program will generate the following result −

The md-autocomplete, an Angular Directive, is used as a special input control with an inbuilt dropdown to show all possible matches to a custom query. This control acts as a real-time suggestion box as soon as the user types in the input area. <md-autocomplete> can be used to provide search results from local or remote data sources. md-autocomplete caches results when performing a query. After first call, it uses the cached results to eliminate unnecessary server requests or lookup logic and it can be disabled.

Angular Material Form Components List

Form Components Example
Autocomplete <mat-form-field> <input type=»text» matInput =»myControl» =»auto»> </mat-form-field> <mat-autocomplete #auto=»matAutocomplete»> <mat-option *ngFor=»let option of options» =»option»>{{option}}</mat-option> </mat-autocomplete>
Checkbox <mat-checkbox>Check me!</mat-checkbox>
Datepicker <input matInput =»picker» placeholder=»Choose a date»> <mat-datepicker-toggle matSuffix =»picker»></mat-datepicker-toggle> <mat-datepicker #picker></mat-datepicker>
Form field <mat-form-field> <input matInput placeholder=»Input»> </mat-form-field>
Input <mat-form-field class=»example-width»> <textarea matInput placeholder=»Leave a comment»></textarea> </mat-form-field>
Radio button <mat-radio-group> <mat-radio-button value=»1″>Option 1</mat-radio-button> <mat-radio-button value=»2″>Option 2</mat-radio-button> </mat-radio-group>
Select <mat-select placeholder=»Select City»> <mat-option *ngFor=»let city of cities» =»city.id»> {{city.name}} </mat-option> </mat-select>
Slider <mat-slider></mat-slider>
Slide toggle <mat-slide-toggle>Slide me!</mat-slide-toggle>

Using Libs themes.scss file

Inside of our styles.scss file, we can import our \_themes.scss file. Assuming we are just changing the primary color and secondary color, we can do the following:

@import '~@angular/material/theming'; @import 'libs/common/styles/_themes';//@include angular-material-theme($mat-light-theme-background);$razroo-theme: mat-light-theme(mat-palette($razroo-primary-blue), mat-palette($razroo-secondary-red));@include angular-material-theme($razroo-theme);

We now have custom themes that we have created. With the architecture we setup, they are available globally to be used by other applications/teams. In addition , using the Angular mat-light-theme function(mat-dark-theme also an option), or app is now using our exclusive theme.

Create a _themes.scss file

Being that we are creating our own themes, the cleanest thing for us to do would be to place it in it’s own themes.scss file. In addition, assuming that the organization is going to build out more applications, giving it the ability to plug and play the companies theme, will really speed up development for other parts of the company. That being said, Razroo best practices is to create a lib folder for styles.

Razroo’s Recommended Styles Lib Folder Structure

and inside of our styles folder, we are going to create a _themes.scss file. Our generated themes using our primary, or secondary colors might look something like this:

Razroo’s Material Primary Blue Color Map

It’s quite a bit of code, but I just wanted to visualize that all of this is created by using the Material Design Palette Generator. I.e. what you can expect when you do the same.

Local Installation

npm install angular-material

The above command will generate the following output −

angular-animate@1.5.2 node_modules\angular-animate

angular-aria@1.5.2 node_modules\angular-aria

angular-messages@1.5.2 node_modules\angular-messages

angular@1.5.2 node_modules\angular

angular-material@1.0.6 node_modules\angular-material

npm will download the files under node_modules > angular-material folder. Include the files as explained in the following example −

Example

Now you can include the css and js file in your HTML file as follows −

<html lang = "en">
   <head>
      <link rel = "stylesheet"
         href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
      
      <script type = "text/javascript">    
         angular.module('firstApplication', );
      </script>
   </head>
   
   <body ng-app = "firstApplication" ng-cloak>
      <md-toolbar class = "md-warn">
         <div class = "md-toolbar-tools">
            <h2 class = "md-flex">HTML 5</h2>
         </div>
      </md-toolbar>
      
      <md-content flex layout-padding>
         <p>HTML5 is the next major revision of the HTML standard superseding HTML
         4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and
         presenting content on the World Wide Web.</p>
         
         <p>HTML5 is a cooperation between the World Wide Web Consortium (W3C) and
         the Web Hypertext Application Technology Working Group (WHATWG).</p>
         
         <p>The new standard incorporates features like video playback and drag-and-drop
         that have been previously dependent on third-party browser plug-ins such as
         Adobe Flash, Microsoft Silverlight, and Google Gears.</p>
      </md-content>
   </body>
</html>

The above program will generate the following result −

Summary

I gathered the most important information to come up with the below comparison. I don’t personally consider the minified JS and minified CSS as an important factor. But I’m sure that it might interest some readers.

Angular Material depends on Angular and two angular modules: angular-animate (ngAnimate) and angular-aria (ngAria). Whereas Material Design Lite has no dependencies.

ngAria provides accessibility support for assistive technologies, such as screen readers. It automatically sets attributes using the corresponding angular directives. For example, it sets the attribute according to the value of the attribute. Material Design Lite does not have any internal accessibility support, but you can take care of it manually.

Being able to use directives to abstract the UI layer is a major plus in my opinion. I prefer writing the following

instead of

Angular Material supports more than 30 components, whereas Material Design Lite supports about 15. That’s because the goal from Material Design Lite is to remain as a lite library, rather than a full fledged UI framework.

Here’s a table that summarizes the main differences between the 2 alternatives:

Angular Material Material Design Lite
Dependencies Angular, ngAnimate, ngAria
Directives Yes No
minified JS ~175KB (excluding dependencies) ~59KB
minified CSS ~175KB ~120KB
Accessibility Built-in (ngAria)
Icons Font File Yes Yes
Components ~30 components ~15 components

Using The Material Light + Dark Theme

Angular offers out of the box in the _theming.scss file a light and dark theme function. The function looks as follows:

It takes in two required parameters:

1. Primary — Primary color

2. Accent — Accent color


and one optional parameter called warn, which by default will be red. So, let’s say we wanted to create a custom theme based on some of the values that Angular provides. We can use the functionality the Angular Material team provides out of the box. In particular, the mat-light theme.

$px-app-primary: mat-palette($mat-green); $px-app-accent: mat-palette($mat-yellow);$px-theme: mat-light-theme($px-app-primary, $px-app-accent); @include angular-material-theme($px-theme);

Now all of our Angular Material components, will be using our unique theme. (Granted this is based on pre-built colors Angular has provided, but you get the point.)

Material Design

Material Design is a design language developed by Google. It aimed to make a consistent experience across all Google apps & platforms (YouTube, Android, Play, Inbox, Gmail, etc.).

Google announced Material Design at the 2014 Google I/O conference.

Material Design emphasizes on responsive interactions, mainly through ripple effects.

Examine how the Material Response makes the element responsive to our touch input:

Upgrade Your JS Go from vanilla JavaScript React

Watch for FREE

Source: https://www.google.com/design/spec/animation/responsive-interaction.html

Material Design also emphasizes on shadow effects to convey depth.

Watch the video again and notice how the element is being lifted on touch.

After the success that Material Design received with the Launch of Android 5, which was the first Material Design implementation, Google decided to release SDKs that allowed developers to integrate Material Design in their apps. Hence, Angular Material and Material Design Lite.

It’s not a competition between Angular Material and Material Design Lite. Google released those 2 SDKs so they can give us more choice depending on our use case.

Установка зависимостей

Установим необходимые зависимости для Angular Material

yarn add @angular/material @angular/cdk @angular/animations

Установим сам Bootstrap

yarn add bootstrap

Отметим, что peer dependency для bootstrap (jquery, popper.js) устанавливать не нужно

warning " > bootstrap@4.3.1" has unmet peer dependency "jquery@1.9.1 - 3".warning " > bootstrap@4.3.1" has unmet peer dependency "popper.js@^1.14.7".

Вы не сможете и не будете использовать стандартную реализацию JS компонентов в Bootstrap. Так как, bootstrap не имеет нативных компонентов для Angular, установим библиотеку с реализацией компонентов bootstrap в angular.

Есть два популярных решения это:

  • Ngx-boostrap

Оба решения имебт свои плюсы и минусы, попробовав каждый из них, вы сможете понять, какая реализация лучше.

В данной статье будем использовать второе решение.

@ng-bootstrap/ng-bootstrap

Также для эффекта swipe’ов и др. событий в мобильных приложениях и браузере, подключим библиотеку Hammer.JS

yarn add hammerjs

Import Material Design and Call Core Styles

The next step, is for us to go ahead and import Material Design in our styles.scss file. The styles.scss file can be found in the root Angular application src folder.

@import '~@angular/material/theming’; // always include only once per project @include mat-core();

You will notice that we are adding a tilda(~)next to the node module folder, containing the sass file we need. This tells sass that the file we would like to import is located inside of the node_modules folder.

What the above does is import the theming.scss file that contains all of the theming variables for material design. We are also calling the mat-core() function, which is a:

Подключение Material

В продолжении серии статей посвященный monorepo для Angular с Nx, склонируем последний проект common-styles и назовем его theming.

Подключим Hammer.JS в main.ts файл приложения

// main.browser.tsimport { enableProdMode } from '@angular/core';import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';import 'hammerjs';...

Добавляем Material icons в styles/common/fonts.scss

// prettier-ignore@import url(//fonts.googleapis.com/css?family=Roboto:100,300,400,500,700&subset=cyrillic,cyrillic-ext);@import url(//fonts.googleapis.com/icon?family=Material+Icons);

Angular Material для корректной работы анимации требует подключения модуля анимации — BrowserAnimationsModule.

Подключим его в AppBrowserModule (или AppModule, если вы не используете Universal)

@NgModule({imports: ,bootstrap: })export class AppBrowserModule {}

Material по-умолчанию не задет тему оформления. Создадим и зададим тему для приложения.

Для этого создадим папку material в styles и создадим там файл theming.scss

@import '~@angular/material/theming';@include mat-core();$candy-app-primary: mat-palette($mat-indigo);$candy-app-accent: mat-palette($mat-pink, A200, A100, A400);$candy-app-warn: mat-palette($mat-red);$candy-app-theme: mat-light-theme($candy-app-primary, $candy-app-accent, $candy-app-warn);@include angular-material-theme($candy-app-theme);

Подробнее с темизацией Angular Material можно ознакомиться здесь.

Для того, чтобы можно было использовать material переменные и миксины в проекте, добавим импорт в styles/utils.scss

// External variables and mixins@import '~@angular/material/theming';...

Из-за того, что невозможно гарантировать, что абсолютно все приложения в workspace Nx будут использовать material и bootstrap, подключим тему непросредственно в проекте theming, а не на уровне common styles в папке styles/style.scss


В папке проекта apps/frontend/theming/src/styles/style.scss, подключим тему

// Import app utils@import './utils';// Import common material theme@import "styles/material/theme";// Import common styles@import 'styles/style';

После того, как тема была подключена, изменим home module и сделаем вывод home component в стандартных компонента Angular Material.

В файле home.common.ts уберем последние преобразования с layouts и оставим просто home component

import { Routes } from '@angular/router';import { HomeComponent } from './containers/home/home.component';export const homeContainers: any[] = ;export const homeRoutes: Routes = ;

Подключим модуль Material Card в home module

import { NgModule } from '@angular/core';import { CommonModule } from '@angular/common';import { MatCardModule } from '@angular/material';import { RouterModule } from '@angular/router';import { TranslateModule } from '@ngx-translate/core';import { homeContainers, homeRoutes } from './home.common';@NgModule({imports: ,declarations: })export class HomeModule {}

И выведем card в home.component.html

<div class="home-page">  <h2>{{ 'home.title' | translate }}</h2>  <mat-card class="home-card">    <div class="home-langs">      <button type="button" (click)="translationFacade.setLanguage('ru')">RU</button> /      <button type="button" (click)="translationFacade.setLanguage('en')">En</button>    </div>    <div class="home-title">{{ 'home.count' | translate }}: {{ counter }}</div>    <div class="home-actions">      <button type="btn btn-default home-action" (click)="add()">        {{ 'home.actions.add' | translate }}      </button>    </div>  </mat-card></div>

Добавим стили, чтобы карточка не сливалась с фоном

@import 'utils';:host {background-color: mat-color($mat-gray, 200);display: block;height: 100vh;}.home-page {padding: 1rem 2rem;}

Запустим проект и посмотрим, что получилось

ng serve frontend-theming

Decision Matrix

The most important question that you should ask yourself is the following: Are you already using AngularJS? Or are you willing to use it?

If the answer to any of those two questions is Yes, then Angular Material is probably the way to go.

Here’s an elaborate matrix that explains all the different scenarios.

Using AngularJs? Complex UI? Preference
Yes Yes Angular Material
Yes No Depends on your experience
No Yes Material Design Lite
No No Material Design Lite

Another important factor would be comparing the to the components available by Material Design Lite. Because sometimes there’s a specific component that matters a lot and of course, you don’t want to reinvent the wheel.

Example

The following example shows the use of shadow classes.

am_whiteframes.htm

<html lang = "en">
   <head>
      <link rel = "stylesheet"
         href = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.css">
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-messages.min.js"></script>
      <script src = "https://ajax.googleapis.com/ajax/libs/angular_material/1.0.0/angular-material.min.js"></script>
      <link rel = "stylesheet" href = "https://fonts.googleapis.com/icon?family=Material+Icons">
      
      <style>
         .frameContainer md-whiteframe {
            background: #fff;
            margin: 30px;
            height: 100px; 
         }
      </style>
      
      <script language = "javascript">
         angular
            .module('firstApplication', )
            .controller('frameController', frameController);
           
         function frameController ($scope) {               
         }	  
      </script>      
   </head>
   
   <body ng-app = "firstApplication"> 
      <div class = "frameContainer" ng-controller = "frameController as ctrl"
         layout = "row" layout-padding layout-wrap layout-fill
         style = "padding-bottom: 32px;" ng-cloak>
         <md-whiteframe class = "md-whiteframe-1dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-1dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-2dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-2dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-3dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-3dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-10dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-10dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-15dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-15dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-20dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-20dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-22dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-22dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-23dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-23dp</span>
         </md-whiteframe>
         
         <md-whiteframe class = "md-whiteframe-24dp" flex-sm = "45" flex-gt-sm = "35"
            flex-gt-md = "25" layout layout-align = "center center">
            <span>.md-whiteframe-24dp</span>
         </md-whiteframe>
      </div>
   </body>
</html>

Grid & Layout

Angular Material Material Design Lite
Desktop percentage(0-100) 12 columns
Tablet percentage(0-100) 8 columns
Phone percentage(0-100) 4 columns
Uses FlexBox Yes Yes
Vertical Layout Yes No
Vertical Centering Yes(out of the box) No (needs manual implementation )
Flex order Yes No
Advanced Yes No

Angular Material’s Grid is much more powerful than Material Design Lite’s grid. Because Material Design Lite is meant for less complex UIs. Angular Material offers a wide range of features when it comes to layouts. You can specify if a layout is horizontal (default) or vertical. This is all done using flexbox. You can also specify child layout alignment, for example or . Check out the .

These are extremely helpful when building complex dashboards and/or advanced page layouts.

Defining the Material Table’s Rows Templates

To define rows in your Material table, you need to include and components inside your table and provide the array which holds the columns list.

Go back to the file and add the following code in the component:

Let’s explain the and directives:

  • First, the directive is used to provide a configuration object for the table header row. In this case, it’s the name of the variable that provides the list of columns,
  • next, the directive is used to provide a configuration for row cells,

The and provide Material styling for the row’s header and cells.

After creating the structure of your Material table, you need to provide the data than the table needs to display.

Attributes

The following table lists out the parameters and description of the different attributes of md-icon.

Sr.No Parameter & Description
1

* md-font-icon

This is the string name of CSS icon associated with the font-face, which will be used to render the icon. Requires the fonts and the named CSS styles to be preloaded.

2

* md-font-set

This is the CSS style name associated with the font library, which will be assigned as the class for the font-icon ligature. This value may also be an alias that is used to lookup the classname; internally use $mdIconProvider.fontSet(<alias>) to determine the style name.

3

* md-svg-src

This is the String URL (or expression) used to load, cache, and display an external SVG.

4

* md-svg-icon

This is the string name used for lookup of the icon from the internal cache; interpolated strings or expressions may also be used. Specific set names can be used with the syntax <set name>:<icon name>. To use icon sets, developers are required to pre-register the sets using the $mdIconProvider service.

5

aria-label

This labels icon for accessibility. If an empty string is provided, icon will be hidden from accessibility layer with aria-hidden = «true». If there’s no aria-label on the icon nor a label on the parent element, a warning will be logged to the console.

6

alt

This labels icon for accessibility. If an empty string is provided, icon will be hidden from accessibility layer with aria-hidden = «true». If there’s no alt on the icon nor a label on the parent element, a warning will be logged to the console.

Creating Our Own Custom Theme


Quite common is that your organization will want to layer their own custom theme outside of the 16 colors that Angular provides. This might manifest it’s self in two scenarioes:

1. A new primary and secondary color

2. In addition to new primary and secondary color, a new background and foreground color as well.

Designers have a tool that allows them to automatically generate the appropriate color in their design by supplying a singular color. Angular developers have that luxury as well. There are tools that will do that for you. My personal favourite is the Material Design Palette Generator. You will then have the ability to click on the clipboard icon, click on the dropdown for Angular JS 2 (Material 2), and copy the scss variable map. It’s really as simple as that.

Material Design Palette Generator Screenshot

Angular Material DataTable Components

DataTable Components Example
Paginator <mat-paginator =»100″ =»10″ =»»> </mat-paginator>
Sort Header <table matSort (matSortChange)=»sortData($event)»> <tr> <th mat-sort-header=»name»>name</th> <th mat-sort-header=»id»>id</th> </tr> <tr *ngFor=»let item of sortedData»> <td>{{item.name}}</td> <td>{{item.id}} </tr> </table>
Table <table mat-table =»dataSource»> <ng-container matColumnDef=»position»> <th mat-header-cell *matHeaderCellDef>id</th> <td mat-cell *matCellDef=»let element»> {{element.id}} </td> </ng-container> <ng-container matColumnDef=»name»> <th mat-header-cell *matHeaderCellDef> Name </th> <td mat-cell *matCellDef=»let element»> {{element.name}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef=»displayedColumns»></tr> <tr mat-row *matRowDef=»let row; columns: displayedColumns;»></tr> </table>

Angular 10 Material Table by Example

To follow this tutorial, it’s better to have completed the previous tutorial(s) where you can setup Angular CLI and create your project. You also need to make sure you have understood the requirements of the vehicle insurance application that you are building throughout the series.

But, if you only care to learn how to use the Angular Material datatable, you simply need to make sure you have the following prerequisites and requirements:

  • Knowledge of TypeScript and Angular,
  • Node.js and npm installed on your machine,
  • Angular CLI 10 installed on your system,
  • An Angular 10 project created,
  • You have some data that you can display in your data-table

That’s it, you are now ready to follow with the next steps.

Layout Directive

Layout directive on a container element is used to specify the layout direction for its children. Following are the assignable values for the Layout Directive −

  • row − Items are arranged horizontally with max-height = 100% and max-width is the width of the items in the container.

  • column − Items are arranged vertically with max-width = 100% and max-height is the height of the items in the container.

For responsive design such as layout to be automatically changed depending upon the device screen size, the layout APIs listed in the following table can be used to set the layout direction for devices with view widths.

Sr.No API & Device width when breakpoint overrides default
1

layout

Sets default layout direction unless overridden by another breakpoint.

2

layout-xs

width < 600px

3

layout-gt-xs

width >= 600px

4

layout-sm

600px <= width < 960px

5

layout-gt-sm

width >= 960px

6

layout-md

960px <= width < 1280px

7

layout-gt-md

width >= 1280px

8

layout-lg

1280px <= width < 1920px

9

layout-gt-lg

width >= 1920px

10

layout-xl

width >= 1920px


С этим читают