目录
一. 在运行上面命令后, 控制台会出现一些选项让开发者选择一些功能:
问题描述
在使用了 npm 下载 Material 后, 项目不能正常使用 Material 组件, 随后又使用官方命令使用 Material 组件, 仍然不能正常使用 Material 组件.
使用的 npm 命令:
npm install --save @angular/material
最后发现, 在执行上面相关命令后, Material 并没有完全自动执行下文 "二. 之后还将执行下面操作:", 随后手动执行 "二. ..." 相关操作, 组件正常运行.
解决方案(按步骤手动执行下面):
官方网站:
使用官方推荐命令会比较好, 主要是官方推介命令会进行相应配套操作, 降低自己操作难度:
ng add @angular/material
一. 在运行上面命令后, 控制台会出现一些选项让开发者选择一些功能:
1. 选择组件的主题, 或者自定义主题(custom). 粗略理解就是页面主题颜色
2. 设置全局样式.
3. 设置浏览器动画.
二. 之后还将执行下面操作:
1. 将相关依赖库加入 package.json 文件中: 主要加入 @angular/material
2. 在 index.html 中添加字体和 icon 资源. 如下:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyAppMaterial</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>
主要是在 <head> 内加入:
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
三. 添加全局 css 样式.
-
去掉
body
的边距 -
为
html
和body
设置height: 100%
-
把 Roboto 设置为默认的应用字体
angular.json
"styles": [ "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", "src/styles.scss" ],
src/styles.scss
/* You can add global styles to this file, and also import other style files */ html, body { height: 100%; } body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }
另外附带 package.json 供大家参考:
dependencies 中下面这两个版本保持一致:
"@angular/material": "^10.2.7",
"@angular/cdk": "^10.2.7",
还需要有
"@angular/animations": "~10.2.0",
{ "name": "my-app-material", "version": "0.0.0", "scripts": { "ng": "ng", "start": "ng serve --port 80", "build": "ng build", "test": "ng test", "lint": "ng lint", "e2e": "ng e2e" }, "private": true, "dependencies": { "@angular/animations": "~10.2.0", "@angular/cdk": "^10.2.7", "@angular/common": "~10.2.0", "@angular/compiler": "~10.2.0", "@angular/core": "~10.2.0", "@angular/forms": "~10.2.0", "@angular/material": "^10.2.7", "@angular/platform-browser": "~10.2.0", "@angular/platform-browser-dynamic": "~10.2.0", "@angular/router": "~10.2.0", "rxjs": "~6.6.0", "tslib": "^2.0.0", "zone.js": "~0.10.2" }, "devDependencies": { "@angular-devkit/build-angular": "~0.1002.0", "@angular/cli": "~10.2.0", "@angular/compiler-cli": "~10.2.0", "@types/node": "^12.11.1", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", "codelyzer": "^6.0.0", "jasmine-core": "~3.6.0", "jasmine-spec-reporter": "~5.0.0", "karma": "~5.0.0", "karma-chrome-launcher": "~3.1.0", "karma-coverage-istanbul-reporter": "~3.0.2", "karma-jasmine": "~4.0.0", "karma-jasmine-html-reporter": "^1.5.0", "protractor": "~7.0.0", "ts-node": "~8.3.0", "tslint": "~6.1.0", "typescript": "~4.0.2" } }