开发学院

您的位置:首页>教程>正文

教程正文

Angular Material 7 滑动开关

  <mat-slide-toggle>用作创建具有Angular Material 样式和动画功能的滑动开关。

  在本章中,我们将展示使用具有Angular Material 样式和动画功能绘制滑动开关控件所需的配置。

创建 Angular 应用

  按照以下步骤创建应用程序

  1.创建一个名为materialApp的项目。

  2.修改app.module.ts, app.component.ts, app.component.css and app.component.htmls。保持其余文件不变。

  3.编译并运行程序。

  下面是修改后的app.module.ts文件内容。

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSlideToggleModule, MatCheckboxModule} from '@angular/material'
@NgModule({
   declarations: [
      AppComponent
   ],
   imports: [
      BrowserModule,
      BrowserAnimationsModule,
      MatSlideToggleModule, MatCheckboxModule,
      FormsModule,
      ReactiveFormsModule
   ],
   providers: [],
   bootstrap: [AppComponent]
})
export class AppModule { }

  下面是修改后的app.component.html的内容.

<mat-slide-toggle
   class = "tp-margin"         
   [checked] = "checked"
   [disabled] = "disabled">
   Slide!
</mat-slide-toggle>
<section class = "tp-section">
   <mat-checkbox class = "tp-margin" [(ngModel)] = "checked">Checked</mat-checkbox>
   <mat-checkbox class = "tp-margin" [(ngModel)] = "disabled">Disabled</mat-checkbox>
</section>

  下面是app.component.css的内容。

.tp-section {
   display: flex;
   align-content: center;
   align-items: center;
   height: 60px;
}
.tp-margin {
   margin: 30px;
}

 下面是修改后的app.component.ts的内容.

import { Component } from '@angular/core';
@Component({
   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']
})
export class AppComponent {
   title = 'materialApp'; 
   disabled = false;
   checked = false; 
}

结果

angular_material7_slider_toggle.jpg

细节

  首先,我们使用mat-checkbox创建了两个复选框,并使用带有变量的ngModel绑定它们。这些属性将用于处理滑动开关。

  然后,我们创建了滑动开关,并展示了它与ts文件中的变量绑定的各种属性。