material-components-web 是一个 Google Material Design 风格的前端组件库,提供丰富的现成组件,例如按钮、表单、弹窗等等。本文将介绍如何使用 npm 包的形式引入该组件库,以及如何在项目中快速启用其中的组件。
安装
要使用 material-components-web,我们首先需要使用 npm 安装该组件库:
npm install --save material-components-web
安装完毕后,我们就可以在项目代码中引入该组件库:
// 引入 CSS 文件 import 'material-components-web/dist/material-components-web.css'; // 引入 JavaScript 模块 import { MDCButton } from 'material-components-web';
使用
现在,我们已经可以在代码中使用 material-components-web 中的组件了。以按钮为例,我们可以这样创建一个 Google 风格的按钮:
<button class="mdc-button"> <span class="mdc-button__ripple"></span> <span class="mdc-button__label">Button</span> </button>
但是,这样创建一个按钮还是比较麻烦的。更好的方式是使用 JavaScript API 来初始化按钮:
<button class="mdc-button" id="my-button"> <span class="mdc-button__ripple"></span> <span class="mdc-button__label">Button</span> </button> <script> const button = new MDCButton(document.querySelector('#my-button')); </script>
这样,我们就可以在页面上直接初始化一个 Google 风格的按钮,并调用其方法(例如 disable()
、enable()
)来控制按钮的状态。
值得一提的是,material-components-web 中的很多组件都支持懒加载(lazy loading):只有当组件第一次初始化时才会加载必要的资源。因此,使用 JavaScript API 来初始化组件是更为稳妥的方式。
示例
下面是一个完整的示例,演示如何在新建项目中引入 material-components-web,并使用其中的按钮组件:
1. 创建项目
首先,使用 Angular CLI 创建一个新项目:
ng new my-app
2. 安装依赖
进入项目目录,并使用 npm 安装 material-components-web:
cd my-app npm install --save material-components-web
3. 引入 CSS 文件
在 angular.json
文件中,在 styles
数组中添加 material-components-web 的 CSS 文件:
{ "build": { "styles": [ "node_modules/material-components-web/dist/material-components-web.css", "src/styles.css" ] } }
4. 创建按钮
在 src/app/app.component.html
文件中,创建一个按钮并给其设置 id:
<button class="mdc-button" id="my-button"> <span class="mdc-button__ripple"></span> <span class="mdc-button__label">Click me</span> </button>
5. 初始化按钮
在 src/app/app.component.ts
文件中,使用 JavaScript API 初始化按钮:
-- -------------------- ---- ------- ------ - ---------- ------------- - ---- ---------------- ------ - --------- - ---- -------------------------- ------------ --------- ----------- ------------ ----------------------- ---------- ----------------------- -- ------ ----- ------------ ---------- ------------- - ----------------- - ----- ------ - --- ------------------------------------------------ - -展开代码
6. 运行项目
使用 ng serve
命令运行项目,并在浏览器中查看效果:
ng serve
到这里,我们就成功地在 Angular 项目中使用了 material-components-web 中的按钮组件。当然,该组件库还有许多其他的组件,可以按照上述步骤类似地使用。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/200882