使用Angular Material Design组件创建UI

在本教程中,我将向您介绍Angular中的Material Design,然后我们将研究如何使用由各种Angular Material组件构建的UI创建一个简单的Angular应用程序。

基于组件的框架(例如Angular,React和Vue.js)的广泛采用已经看到越来越多的预构建UI组件集合可用。 使用此类集合可以帮助开发人员快速创建具有专业外观的应用程序。

什么是材料设计?

材料设计(代号为Quantum Paper )是一种视觉语言,可用于创建数字体验。 这是一套跨平台和设备的交互性,运动性和组件性原则和指南,可简化团队设计其产品的设计工作流程。

通过Material组件,您可以创建具有强大的模块化,主题化和自定义功能的专业UI。

角材料介绍

Angular MaterialAngular的材料设计原则和准则的实现。 它包含各种UI组件,例如:

  • 表单控件(输入,选择,复选框,日期选择器和滑块等),
  • 导航模式(菜单,sidenav和工具栏)
  • 布局组件(网格,卡片,选项卡和列表)
  • 纽扣
  • 指标(进度条和微调器)
  • 弹出窗口和模态
  • 带有标题和分页等的数据表

要求

在继续本教程之前,您需要确保已安装有Node(6.9.0+)和NPM(3+)的开发机器。

您还需要安装Angular CLI。 如果不是这种情况,只需在终端或命令提示符中运行以下命令:

npm install -g @angular/cli

使用Angular CLI创建项目

现在,让我们使用Angular CLI创建Angular项目。 只需运行以下命令:

ng new angularmaterialdemo

然后,您可以通过运行以下命令来服务您的应用程序:

cd angularmaterialdemo
ng serve

该应用程序将在http://localhost:4200

由于我们将演示不同的Angular Material组件,因此我们需要为一个简单的演示应用程序创建一些Angular组件和路由配置,因此请继续使用CLI生成组件:

ng g component login
ng g component CustomerList
ng g component CustomerCreate

接下来,打开src/app/app.module.ts并添加路由器配置:

/*...*/

import { RouterModule, Routes } from  '@angular/router';

/*...*/

const  appRoutes:  Routes  = [
{ path:  'customer-list', component:  CustomerListComponent },
{ path:  'customer-create', component:  CustomerCreateComponent },
{
path:  'login',
component:  LoginComponent
},
{ path:  '',

redirectTo:  '/login',

pathMatch:  'full'

},
];

角材料入门

现在,我们有了一个基本的应用程序,让我们开始安装Angular Material及其不同的依赖项,以启用手势和动画等不同的功能。

安装Angular材质和Angular CDK

首先从npm安装Angular Material和Angular CDK。

回到您的终端并运行以下命令:

npm install --save @angular/material @angular/cdk

添加HammerJS进行手势支持

诸如mat-slide-togglemat-slidermatTooltip都需要HammerJS库提供手势支持,因此您需要安装它才能获得这些组件的全部功能。 只需在终端中运行以下命令:

npm install --save hammerjs

接下来,打开src/main.js (应用程序的入口)并导入hammerjs

import 'hammerjs';

添加主题

Angular Material有很多预先构建的主题。 要使用主题,只需将其导入styles.css

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

您可以在本指南中找到有关主题的更多信息。

添加角度材质图标

Angular Material带有用于图标的mat-icon组件,因此您需要先加载图标字体,然后才能使用它。

将以下标记添加到index.html文件:

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

将动画与角度材质组件一起使用

最后一件事是启用动画。 一些组件依赖于Angular动画模块进行高级过渡,因此您需要安装@angular/animations模块,并在应用程序模块配置中包含BrowserAnimationsModule

首先,回到您的终端并运行以下命令:

npm install --save @angular/animations

接下来,打开src/app/app.module.ts并添加以下代码:

/* ... */
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
/*...*/
imports: [
BrowserModule,
BrowserAnimationsModule,
],
})
export  class  AppModule { }

导入角材料零部件

在使用任何Angular Material组件之前,您必须导入其模块。 每个组件都有其自己的模块,因此您可以仅包含要使用的组件。

另一种方法是创建一个单独的模块并导入您需要使用的所有Angular Material组件,然后将该模块简单地包含在您的应用程序模块中。

因此,继续创建src/app/material.module.ts文件,然后添加以下内容:

import { NgModule } from  '@angular/core';
import {MatNativeDateModule,MatSnackBarModule,MatIconModule,MatDialogModule, MatButtonModule, MatTableModule, MatPaginatorModule , MatSortModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCard, MatCardModule, MatFormField, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule } from  '@angular/material';
import {MatDatepickerModule} from  '@angular/material/datepicker';
import {MatRadioModule} from  '@angular/material/radio';
import {MatSelectModule} from  '@angular/material/select';
import {MatSliderModule} from  '@angular/material/slider';
import {MatDividerModule} from  '@angular/material/divider';

@NgModule({
imports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule,MatTableModule,MatTabsModule, MatCheckboxModule, MatToolbarModule, MatCardModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],
exports: [MatTabsModule,MatDividerModule,MatSliderModule,MatSelectModule,MatRadioModule,MatNativeDateModule,MatDatepickerModule,MatSnackBarModule,MatIconModule,MatDialogModule,MatProgressSpinnerModule,MatButtonModule,MatSortModule, MatCheckboxModule, MatToolbarModule, MatCardModule,MatTableModule,MatTabsModule, MatFormFieldModule, MatProgressSpinnerModule, MatInputModule, MatPaginatorModule],

})

export  class  MyMaterialModule { }

接下来,将此模块包含在src/app/app.module.ts

import { MyMaterialModule } from  './material.module';

/*...*/

@NgModule({

/*...*/

imports: [

/*...*/
MyMaterialModule,
],
/*...*/
})

export  class  AppModule { }

就是这样:您现在可以在Angular应用程序中使用导入的Angular Material组件。

为应用程序创建UI

您先前已经创建了应用程序组件并添加了路由器配置。 现在,让我们使用Angular Material组件为不同的组件构建UI。

构建AppComponent的UI

继续打开src/app/app.component.html ,然后添加:

  • 一个Material工具栏,带有三个Material按钮( mat-button ),用于链接到应用程序组件
  • 路由器出口<router-outlet> ,将在其中插入与路由器路径匹配的组件。

这是组件的HTML代码:

<mat-toolbar  color="primary"  class="fixed-header">
<mat-toolbar-row>
<span><img  src="./assets/logo.png"  style="width:50px;"></span>
<a  mat-button  routerLink="/customer-list"  routerLinkActive="active">Customers</a>
<a  mat-button  routerLink="/customer-create">Create Customer</a>
<a  mat-button  routerLink="/login">Login</a>
</mat-toolbar-row>
</mat-toolbar>
<main>
<router-outlet  style="margin-top: 80px;"></router-outlet>
</main>

通过添加一些样式,这是工具栏的外观:

Angular Material:首先看一下工具栏

要创建工具栏,请使用<mat-toolbar>组件,然后使用<mat-toolbar-row>组件在工具栏中创建一个或多个行。

请注意,我们已导入MatToolbarModuleMatButtonModule模块从@angular/materialmaterial.module.ts

您还可以使用其他导航组件,例如菜单边栏

为登录组件构建UI

在为应用程序的根组件创建UI之后,让我们为登录组件创建UI。

打开src/app/login/login.component.html并添加以下HTML代码。 添加一个Angular Material卡以包含登录表单:

<mat-card  class="login-card">
<mat-card-header>
    <mat-card-title>Login</mat-card-title>
</mat-card-header>
    <mat-card-content>
    <!-- The form goes here -->
    </mat-card-content>

<mat-card>组件用作文本,照片和操作的单对象容器。 在docs中找到有关卡片的更多详细信息。

接下来,在卡片的内容部分中,添加HTML表单:

    <form  class="login-form">
        <!-- Form elements are here -->
    </form>

现在,我们添加两个输入来获取用户的用户名和密码凭据:

<mat-form-field>
<input  matInput  placeholder="Username" [(ngModel)]="username"  name="username"  required>
</mat-form-field>
<mat-form-field>
<input  matInput  placeholder="Password" [(ngModel)]="password"  type="password"  name="password"  required>
</mat-form-field>

许多Angular Material组件需要包裹在一个 组件具有常见的文本字段样式,例如下划线,浮动标签和提示消息。

这些是设计为包装在<mat-form-field>

最后,在卡片的“操作”部分,为登录操作添加一个“角度材料”按钮:

<mat-card-actions>
    <button  mat-raised-button (click)="login()"  color="primary">Login</button>
</mat-card-actions>
</mat-card>

要创建Angular Material按钮,您只需使用本机HTML <button><a>元素并添加Material属性,例如mat-buttonmat-raised-button 。 有关更多详细信息,请检查docs

这是登录表单的外观:

登录表格

如果登录成功( 用户名:demo,密码:demo ),则用户将被重定向到CustomerList组件。 否则,用户将收到错误消息:“您的登录信息不正确!”

创建错误模态对话框

MatDialog可用于创建和打开模式对话框。 该对话框需要加载组件,因此首先创建一个Angular组件,以显示传递的错误消息。

创建src/app/error.component.ts ,然后添加以下代码:

import {Component, Inject, Injectable} from  '@angular/core';

import {MatDialogRef, MAT_DIALOG_DATA, MatDialog} from  '@angular/material';

@Component({
templateUrl:  'error.component.html'
})
export  class  ErrorComponent {
    constructor(private  dialogRef:  MatDialogRef<ErrorComponent>, @Inject(MAT_DIALOG_DATA) public  data:  any) {
    }
    public  closeDialog() {
        this.dialogRef.close();
    }
}

将使用MatDialog创建和打开此组件,以便它可以注入MatDialogRef ,该MatDialogRef为打开的对话框提供句柄,并且可以用来关闭对话框并在对话框关闭时接收通知。 ( closeDialog()方法使用此引用来关闭对话框。)

我们的错误组件需要一种方法来获取要向用户显示的错误消息。 (当使用MatDialog open方法打开组件时,将传递该消息。)您可以使用MAT_DIALOG_DATA注入令牌访问对话框组件中的数据,该注入令牌可以从'@angular/material'导入,然后使用@Inject()注入到组件中@Inject()

接下来,创建src/app/error.component.html并添加以下代码:

<h2  mat-dialog-title>Error</h2>
<mat-dialog-content  class="error">{{data.message}}</mat-dialog-content>
<mat-dialog-actions>
<button  mat-raised-button (click)="closeDialog()">Ok</button>
</mat-dialog-actions>

我们使用许多可用的指令来构造对话框组件:

  • mat-dialog-title :用于对话框标题,需要应用于标题元素<h1><h2>等。
  • <mat-dialog-content> :用于对话框的可滚动内容
  • <mat-dialog-actions> :用作对话框动作的容器。

接下来,打开src/app/app.module.ts并将此组件添加到模块中:

@NgModule({

declarations: [

/*...*/
    ErrorComponent
],

imports: [/*...*/
],
entryComponents: [ErrorComponent],
/*...*/
})

export  class  AppModule { }

现在,我们将login()方法(以触发错误对话框)添加到LoginComponent

import { Component, OnInit } from  '@angular/core';
import { MatDialog, MatDialogRef } from  '@angular/material';

/* ... */

@Component({
/* ... */
})
export  class  LoginComponent{

    public  username:  string  =  "";
    public  password:  string  =  "";


    constructor(private  dialog:  MatDialog, private  router:  Router) { }
    login(){
        if(this.username  ===  "demo"  &&  this.password  === "demo")
        {
            this.router.navigate(['customer-list']);
        }
        else
        {
            this.dialog.open(ErrorComponent,{ data: {
            message:  "Your login information are incorrect!"
            }});
        }
    }
}

我们只需注入MatDialog组件,并使用它打开一个对话框(如果用户凭据不正确),其中ErrorComponent组件和一个将要传递的数据的配置对象。 open()方法返回MatDialogRef的实例。

这是错误对话框的屏幕截图:

错误对话框的屏幕截图

您可以从docs中找到有关对话框的更多信息。

为CustomerList组件构建UI

对于CustomerList组件,我们将使用不同的Angular Material组件,最重要的是:

打开src/app/customer-list/customer-list.component.html并添加以下标记:

<div  class="mat-elevation-z8">
<!-- Other contents here -->
</div>

mat-elevation-z8类是Angular Material高程类,它允许您沿z轴在元素之间添加间隔。 您可以从此链接中找到更多详细信息。

添加加载微调器

当数据仍在加载时,我们使用<mat-spinner>来显示微调器,我们正在使用setTimeout()函数进行模拟:

<mat-spinner [style.display]="loading ? 'block' : 'none'"></mat-spinner>

如果loading变量等于true ,则为CSS display属性分配block值。 否则,将不分配none ,这使其消失。

您需要向组件类添加一个加载变量,该变量初始值为true

    loading  =  true;
    /*...*/
    constructor() {}
ngOnInit():  void {

    setTimeout(() => {

        this.loading  =  false;

    }, 2000);

    /*...*/
使用数据源添加数据表

然后,我们使用<mat-table>创建一个Material数据表,该<mat-table>仅在loading等于false时才显示:

<mat-table [style.display]="loading === false ? 'block' : 'none'" #table [dataSource]="dataSource">
<!-- Other contents here -->
</mat-table>

数据表具有dataSource属性,该属性用于为表提供数据。 您可以简单地将数据数组传递给表,但是对于实际使用案例,您需要使用Angular Material提供的高级数据源(例如MatTableDataSource ,该数据源封装了用于分页,排序和过滤等高级操作的逻辑:

export  class  CustomerListComponent  implements  OnInit {

    customers:  Customer[] = [
    { id:1, name:'Customer 001',job:'Programmer'},
    /*...*/
    ];

    dataSource  =  new  MatTableDataSource<Customer>(this.customers);
添加列模板

对于每个列定义,您需要为其标题和行单元格提供唯一的名称及其内容。 例如,这是用于显示客户ID的列:

<ng-container  matColumnDef="id">
<mat-header-cell *matHeaderCellDef> CustomerId </mat-header-cell>
<mat-cell *matCellDef="let customer"> {{customer.id}} </mat-cell>
</ng-container>

这是一个简单的列定义,名称为id 。 标题单元格包含文本CustomerId ,每个行单元格将呈现每行数据的id属性。

以类似的方式,您可以添加其他列定义。

对于“操作”列,我们使用两个Angular Material图标:用Material按钮包装的deleteedit

<ng-container  matColumnDef="operations">

<mat-header-cell *matHeaderCellDef  mat-sort-header> Operations </mat-header-cell>

<mat-cell *matCellDef="let element">  <button  mat-button  color="primary" (click)="deleteCustomer(element.id)"><mat-icon>delete</mat-icon>

</button>  <button  mat-button  color="primary" (click)="editCustomer(element.id)"><mat-icon>edit</mat-icon></button>  </mat-cell>

</ng-container>
添加行模板

在定义列模板之后,您需要定义行模板,因此首先需要向组件添加一个包含您必须具有的列列表的变量:

displayedColumns  = ['id', 'name', 'job', 'operations'];

接下来,您需要在<mat-table>的内容中添加<mat-header-row><mat-row> <mat-table>并提供列列表作为输入:

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
添加分页

您只需在<mat-table>之后添加<mat-paginator>组件,即可向数据表添加<mat-paginator>

<mat-paginator #paginator [style.display]="loading === false ? 'block' : 'none'" [pageSize]="5"></mat-paginator>

使用MatTableDataSource好处之一是,您只需向数据源提供MatPaginator ,即可实现分页。

首先,请确保您导入MatPaginatorModulematerial.module.ts 。 然后,您需要获取paginator指令:

@ViewChild(MatPaginator) paginator:  MatPaginator;

最后,您只需将分页器传递到表的数据源:

ngAfterViewInit() {
    this.dataSource.paginator  =  this.paginator;
}
添加排序

使用MatTableDataSource您还可以通过仅添加一些内容来进行开箱即用的排序。

首先,请确保已在模块中导入了MatSortModulematerial.module.ts )。

接下来,将matSort指令添加到<mat-table>组件,然后将mat-sort-header添加到需要进行排序的每个列标题单元格中。

例如,让我们在name列中添加排序:

<ng-container  matColumnDef="name">
<mat-header-cell *matHeaderCellDef  mat-sort-header> Name </mat-header-cell>
<mat-cell *matCellDef="let customer"> {{customer.name}} </mat-cell>
</ng-container>

最后,您需要向数据源提供MatSort指令,它将自动进行排序:

import {MatTableDataSource, MatPaginator, MatSort} from  '@angular/material';
/*...*/
export  class  CustomerListComponent  implements  OnInit {

@ViewChild(MatSort) sort:  MatSort;

ngAfterViewInit() {
    /*...*/
    this.dataSource.sort  =  this.sort;
}

您还可以向表添加过滤和选择。 检查文档以获取更多信息。

使用MatTableDataSource可为您提供许多内置功能,但仅支持客户端分页。 对于服务器端分页或其他自定义功能,您需要创建自定义数据源

对于自定义数据源,您将需要侦听分页器的(page)事件以实现分页,并(matSortChange) sort的(matSortChange)事件以实现数据排序。

这是CustomerList组件的屏幕截图:

CustomerList组件

添加SnackBar通知

首先,请确保已将MatSnackBarModule导入到模块中。 接下来,将MatSnackBar导入并注入到您的组件中,然后只需调用MatSnackBar实例的open()方法:

import {MatSnackBar} from  '@angular/material';
/*...*/
constructor(public  snackBar:  MatSnackBar) {}

deleteCustomer(id){
    let  snackBarRef  =  this.snackBar.open(`Deleting customer #${id}`);
}
editCustomer(id){
    let  snackBarRef  =  this.snackBar.open(`Editing customer #${id}`);
}

为CustomerCreate组件构建UI

对于CustomerCreate组件,我们将使用一堆Angular Material组件,例如:

  • 卡组件( <mat-card>
  • 选项卡组件( <mat-tab><mat-tab-group>
  • 标签( <mat-label> )和输入( <input matInput><textarea matInput> )组件
  • 表单字段( <mat-form-field> )组件
  • 复选框( <mat-checkbox> )组件
  • 日期选择器( <mat-datepicker> )组件
  • 单选按钮( <mat-radio-button )组件
  • 选择( <mat-select> )组件。

因此,打开src/app/customer-create/customer-create.component.html并开始添加包含客户创建表单的卡组件:

<mat-card  class="my-card">
<mat-card-header>
    <mat-card-title>Create Customer</mat-card-title>
</mat-card-header>

    <mat-card-content>
    <!-- The form goes here -->
    </mat-card-content>
    <mat-card-actions>
    <!-- Actions go here -->
    </mat-card-actions>
</mat-card>

在卡片内容部分,我们添加一个HTML表单:

<form  class="my-form">
<!-- Form fields here -->
</form>

接下来,让我们使用Angular Material选项卡组件将表单字段组织到水平选项卡中。 在form元素内,添加以下代码以创建两个带有General InformationOther Information标签的选项卡:

<mat-tab-group>
<mat-tab  label="General Information"  class="my-tab">
<!-- Form fields here -->
</mat-tab>
<mat-tab  label="Other Information"  class="my-tab">
<!-- Form fields here -->
</mat-tab>
</mat-tab-group>

在每个选项卡中,我们将添加一个HTML表以将表单字段组织到表单元格中:

<table  style="width: 100%"  cellspacing="10">
<tr>
    <td> <!-- Form fields here --> </td>
</tr>
</table>

在第一个选项卡中添加以下内容。 在表格行/单元格内,为客户名称添加一个字段:

<mat-form-field>
    <mat-label>Name</mat-label>
    <input  matInput  placeholder="Name" [(ngModel)]="name"  name="name"  required>
</mat-form-field>

接下来为客户地址创建输入:

<mat-form-field>
    <mat-label>Address</mat-label>
    <textarea [(ngModel)]="address"  matInput></textarea>
</mat-form-field>

最后,为客户电子邮件创建一个输入字段:

<mat-form-field>
    <mat-label>Email</mat-label>
    <input  matInput  placeholder="Email" [(ngModel)]="email"  name="email">
</mat-form-field>

我们使用<mat-label>创建标签,使用<input matInput />创建输入字段,并使用<textarea matInput>创建文本区域字段。

对于第二个选项卡,添加以下内容。 在表格的第一行/单元格中,添加公司? 复选框:

<mat-checkbox [checked]="isCompany">Is company?</mat-checkbox>

checked属性确定复选框是否被选中。

接下来,添加一个带有日期选择器的日期输入,该日期选择器包装在Angular Material表单字段中:

<mat-form-field>
    <mat-label>Created At</mat-label>
    <input  [value]="createdAt.value" matInput [matDatepicker]="picker"  placeholder="Date of creation">
    <mat-datepicker-toggle  matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
</mat-form-field>

Angular mMaterial文档中所述

日期选择器允许用户通过文本输入或从日历中选择日期来输入日期。 它由几个可以协同工作的组件和指令组成。

接下来,添加一组单选按钮以选择客户的性别:

<mat-label>Gender</mat-label>
<mat-radio-group [(value)]="selectedGender">
    <mat-radio-button  value="male">Male</mat-radio-button>
    <mat-radio-button  value="female">Female</mat-radio-button>
</mat-radio-group>

要在组内获取当前选定的单选按钮,只需将变量绑定到value属性。

最后,添加选择字段以选择潜在客户/客户的来源:

<mat-form-field>
    <mat-label>Lead Source</mat-label>
        <mat-select [(value)]="selectedSource" placeholder="Source">
        <mat-option>None</mat-option>
        <mat-option value="email">Email Marketing</mat-option>
        <mat-option value="social">Social Media</mat-option>
        <mat-option value="affiliate">Affiliate</mat-option>
    </mat-select>
</mat-form-field>

<mat-select>组件支持对value属性的双向绑定,而无需Angular形式。

现在,让我们添加一个按钮,以根据表单信息创建客户:

<mat-card-actions>
    <button  mat-raised-button (click)="createCustomer()"  color="primary">Create</button>
</mat-card-actions>

现在,您需要创建绑定到这些控件的变量。 在src/app/customer-create/customer-create.component.ts ,将以下代码添加到组件类:

name:  string  =  "";
email:  string  =  "";
job:  string  =  "";
address:  string  =  "";
selectedSource:  string  =  "email";
selectedGender:  string  =  "male";
isCompany  :  boolean  =  false;
createdAt  =  new  FormControl(new  Date());
public  createCustomer(){
/* logic to create a customer from the form information*/
}

这是组件UI的屏幕截图:

组件UI

您可以在此处观看此演示。

结论

凭借国际化,可访问性,无错误的缺陷和高性能,Angular Material旨在使用Angular并基于Material设计规范来构建一组高质量的UI组件。

在本教程中,我们使用带有各种UI组件的Angular Material构建了一个简单的UI。 您可以从Angular Material文档中找到完整的可用Angular Material组件集。

您可以在GitHub存储库中找到我们在整个教程中构建的演示的源代码。

From: https://www.sitepoint.com/angular-material-design-components/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值