GVKun编程网logo

notes:Get Started with Angular

20

在本文中,您将会了解到关于notes:GetStartedwithAngular的新资讯,并给出一些关于5ThingsToKnowBeforeYouGetStartedWithAngulerJS、An

在本文中,您将会了解到关于notes:Get Started with Angular的新资讯,并给出一些关于5ThingsToKnowBeforeYouGetStartedWithAngulerJS、Angular Starter Kit —— Angular 2.0 迁移准备工具 (TypeScript)、Angular 学习笔记 (Angular 12 get started)、Angular 小试牛刀[1]-Getting Started的实用技巧。

本文目录一览:

notes:Get Started with Angular

notes:Get Started with Angular

https://egghead.io/courses/get-started-with-angularhttps://egghead.io/lessons/angular-2-say-hello-world-to-angular-2notes:1 install angular js2 simple.ts define <app-simple-form>app.component.ts use <app-simple-form>selector: 'app-simple-form' //it is outest(name) for templatetemplate: ``3<input #myInput type="text">button (click)="onClick(myInput.value)" // bind deal with function and pass parameterexport class SimpleFormComponent implements ... {onClick(value) { //deal with functionconsole.log(value);}}4: it is the same with 35 import ./Mail.service //import[providers]: [MailService] //providerstemplate: `{{mail.message}} //use`export class SimpleFormComponent implements ... {constructor (private mail:MailService) //define}6remove import MailServicetemplate: `{{mail.message}} //use`providers:[{provide:'mail',useClass:MailService}{provide:'api',"http://localhost:3000"}]export class SimpleFormComponent implements ... {constructor (@Inject('mail'),private mail@Inject('api'),private api) //Inject providers(don;t use import service)}7 *ngFor ="let message of mail.messages"8 @Input (pass value from app.component.ts to simple.ts)<app-simple-form *ngFor ="let message of mail.messages">// it is cool. ngFor pass value message to app-simple-form{{message}}[message]="message"</app-simple-form>template: `{{message}} //use (passed value)`export class SimpleFormComponent implements OnInit {@input message //receive [message] pass value}9 [(ngModel)]template'{{message}}<input #myInput type="text" [(ngModel)]="message">'export class SimpleFormComponent implements OnInit {@input message //the message(ngModel) is input}10 @output<app-simple-form *ngFor ="let message of mail.messages">// it is cool. ngFor pass value message to app-simple-form{{message}}[message]="message"(update)="onUpdate(messge.id)" //bind function like (click)</app-simple-form>export class AppComponent {onUpdate(event) {this.message = this.messages.map (m=>m.id===id ? {id,text} : m}}template: `<input #myInput type="text" [(ngModel)]="message"><button (click)="update.emit{{text:message}}">Click me!</button> //trigger emit. pass "text:message" to (update),then call onUpdate`export class SimpleFormComponent implements OnInit {@input() message //receive [message] pass value@output() update = new EventEmitter();}11 css12 css<input[ngClass]="{mousedown:isMousedown}" //use css with variable to control(mousedown)="isMousedown = true"(mouseup)="isMousedown = false" >styles: [.mousedown { //css with "." to startborder: 2px solid green;}]

5ThingsToKnowBeforeYouGetStartedWithAngulerJS

5ThingsToKnowBeforeYouGetStartedWithAngulerJS

1. AngularJS is Entirely Client-Side

AngularJS is written in JavaScript, and it functions entirely on the client side. This means two things for your app. First, you can run AngularJS in any browser that can execute JavaScript, making deployment a snap. Secondly, you can drop AngularJS into any project without significant back-end modifications. This greatly reduces the risk in adopting AngularJS for the front-end display of your app. AngularJS is built off of HTML attributes, making enabling processing of data a fairly quick process, though in order to use AngularJS effectively you’ll likely have to rewrite a portion of your presentation layer.

2. AngularJS is Focused on Data

AngularJS is designed to separate your presentation layer from your business logic layer. It ties the HTML structure of a web page into underlying JavaScript data models, and allows the app to make significant changes to the data without performing the typical extensive DOM manipulations used in other JavaScript libraries. AngularJS follows a Model-View-Controller (MVC) pattern, which encourages loose coupling between presentation, data, and logic. The data for a page in an AngularJS application can come from any of the standard locations, including static or dynamic JSON data obtained from a server or a web API call, as well as being hard-coded into the page.

3. AngularJS Provides a Declarative UI

Most modern apps use JavaScript in various ways to present and manipulate the application’s data. This leads to convolutions in logic where the HTML of a web page needs to be nearly constantly modified and rebuilt in order to present information developed using the procedural programming inherent in JavaScript’s design. AngularJS, on the other hand, takes a declarative approach to data presentation that more closely mimics the intent behind the design of HTML. In essence, AngularJS lets you focus on what is presented, as opposed to the procedural focus on how it is presented.

4. AngularJS Data Objects are POJO

All objects in AngularJS are POJOs, which stands for Plain Old Java(Script) Objects. What this means is that you have all the standard functionality of JavaScript available for object manipulation, allowing you to easily add and remove properties from your objects, and make use of all the built-in collection handlers to loop through your data at will. This results in cleaner code that is more quickly understood by developers, and removes the need for adding special case functions to your data objects in order to get the behavior you want.

5. AngularJS is Built for Testing

Unit and functional testing produce more robust, dependable code. AngularJS was developed with this ideal in mind, and is designed from top to bottom to make testing a relatively painless process. AngularJS uses Dependency Injection (DI) to pass information around, allowing your tests to easily override the function calls and inject appropriate mock data. This is important for writing robust unit tests that isolate the functionality being tested. There are also a number of tools built into AngularJS, such as a mock HTTP provider, that make writing larger functional tests a more dependable endeavor. Finally, there are numerous open-source tools for running test suites in AngularJS, including Karma for running tests and Jasmine for behavior-driven testing

Conclusion

AngularJS is a powerful tool which, when used correctly, can make your presentation layer both more maintainable and more robust. With its focus on data-presentation as a declarative effort, it more closely mimics HTML and its robust interpretations across multiple scenarios. By keeping the above items in mind, you can help direct your development organization in how it uses AngularJS to enhance your application’s data presentation, and prevent long-term pitfalls that can add unnecessary costs and complexity to the development process.

Build your Bootstrap + Angular app with Backand today. – Get started now.

Angular Starter Kit —— Angular 2.0 迁移准备工具 (TypeScript)

Angular Starter Kit —— Angular 2.0 迁移准备工具 (TypeScript)

angular-next-starter-kit 是使用 Angular 1.x 开发的应用准备迁移到 Angular 2.0 的种子项目。

Angular 学习笔记 (Angular 12 get started)

Angular 学习笔记 (Angular 12 get started)

Angular 12 视乎比以往更稳定了. 

这里记入一般的 get started 结构和做法. 

 

第 1 步, 创建项目.

ng new project --create-application=false

默认会自动创建 app, 先关掉它.

 

第 2 步, 装 eslint 和 prettier 

早期 ng 是用 tslint 的, 后来废弃了, 现在改用 eslint 

https://github.com/angular-eslint/angular-eslint 这个是第三方的,但是做的很好一下.

ng add @angular-eslint/schematics
ng config cli.defaultCollection @angular-eslint/schematics

然后就安装 Prettier - Code formatter vscode 插件

https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode

setup vs code setting 

"editor.defaultFormatter": "esbenp.prettier-vscode",
"prettier.singleQuote": true,
"editor.formatOnSave": true,
"eslint.options": {
  "extensions": [".ts", ".html"]
},
"eslint.validate": [
  "javascript",
  "typescript",
  "html"
],
"editor.codeActionsOnSave": {
    "source.fixAll.tslint": true,
    "source.fixAll.eslint": true
},
"editor.detectIndentation": false,

然后安装 prettier

yarn add prettier --dev

要让 prettier 和 eslint 一起工作. 我们需要安装一些 prettier 的 plugin

yarn add eslint-plugin-prettier eslint-config-prettier --dev

然后就创建 app

ng g app control-panel --routing --style=scss --prefix=cp

每一个 app 或 lib 都会自带 .eslintrc.json, 尽量不要使用全局的, best practice 是每一个 app 或 lib 独立管理 (虽然会有重复的设置啦, 但是不多啦)

由于我使用 eslint standard config 所以我要装

yarn add eslint-config-standard eslint-plugin-import eslint-plugin-node eslint-plugin-promise --dev

这个是最终版本的 eslintrc.json, 所以我没有使用 root eslintrc.json 然后我使用了 eslint standard config, 然后我没有 e2e, 其它的都是安装官网配置的了. 

{
  "root": true,
  // "extends": "../../.eslintrc.json", // we don''t have root file, so use root: true instead
  "ignorePatterns": [
    "!**/*"
  ],
  "overrides": [{
      "files": [
        "*.ts"
      ],
      "extends": [
        "standard",
        "plugin:@angular-eslint/recommended",
        "plugin:@angular-eslint/template/process-inline-templates",
        "plugin:prettier/recommended"
      ],
      "plugins": [
        "@typescript-eslint"
      ],
      "parserOptions": {
        "project": [
          "projects/control-panel/tsconfig.app.json",
          "projects/control-panel/tsconfig.spec.json"
          // "projects/control-panel/e2e/tsconfig.json" // we don''t have e2e Now
        ],
        "createDefaultProgram": true
      },
      "rules": {
        "space-before-function-paren": "off",
        "no-multiple-empty-lines": "off",
        "no-new": "off",
        "no-extend-native": "off",
        "prettier/prettier": ["error", {
          "singleQuote": true,
          "endOfLine": "auto" // refer: https://stackoverflow.com/questions/53516594/why-do-i-keep-getting-delete-cr-prettier-prettier
        }],
        "@angular-eslint/directive-selector": [
          "error",
          {
            "type": "attribute",
            "prefix": "cp",
            "style": "camelCase"
          }
        ],
        "@angular-eslint/component-selector": [
          "error",
          {
            "type": "element",
            "prefix": "cp",
            "style": "kebab-case"
          }
        ]
      }
    },
    {
      "files": [
        "*.html"
      ],
      "extends": ["plugin:@angular-eslint/template/recommended"],
      "rules": {}
    },
    {
      "files": ["*.html"],
      "excludedFiles": ["*inline-template-*.component.html"],
      "extends": ["plugin:prettier/recommended"],
      "rules": {
        "prettier/prettier": ["error", {
          "parser": "angular"
        }]
      }
    }
  ]
}

 

第 3 步 安装 library

ng g lib stooges --prefix=s

通常一个 project 里面会有好几个 app, shared code 就可以做一个 library 来管理, 以后要发布也比较容易.

由于我没有要做成发布的版本,所以我需要修改一下 ts config

 

 

第 4 步 安装 tailwind css 和 stylelint

tailwind 火, 无论如何都是要跟风一下的啦.

yarn add tailwindcss postcss autoprefixer stylelint stylelint-scss stylelint-config-recommended stylelint-prettier stylelint-config-prettier --dev

tailwind.config.js

module.exports = {
  purge: {
    enabled: true,
    content: [''./projects/*/src/**/*.html''],
  },
  darkMode: false, // or ''media'' or ''class''
  theme: {
    extend: {},
  },
  variants: {
    extend: {},
  },
  plugins: [],
};

stylelint.config.js

module.exports = {
  extends: [''stylelint-config-recommended'', ''stylelint-prettier/recommended''],
  plugins: [''stylelint-scss''],
  rules: {
    ''at-rule-no-unkNown'': null,
    ''scss/at-rule-no-unkNown'': [
      true,
      {
        ignoreAtRules: [
          ''tailwind'',
          ''apply'',
          ''variants'',
          ''responsive'',
          ''screen'',
        ],
      },
    ],
    ''declaration-block-trailing-semicolon'': null,
    ''no-descending-specificity'': null,
    ''prettier/prettier'': [
      true,
      {
        endOfLine: ''auto'', // refer: https://stackoverflow.com/questions/53516594/why-do-i-keep-getting-delete-cr-prettier-prettier
      },
    ],
  },
};

vs code setting 

"css.validate": false,
"scss.validate": false,
"stylelint.enable": true,

 

到这里我们就有了一个 project 通常会用到的结构了. 

 

总结

以上是小编为你收集整理的Angular 学习笔记 (Angular 12 get started)全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

原文地址:https://www.cnblogs.com/keatkeat/p/14821676.html

Angular 小试牛刀[1]-Getting Started

Angular 小试牛刀[1]-Getting Started

首先,Angular2 与 Angular1.x 版本没有多大关系,甚至可以说是两个完全不一样的框架,故 Angular 指的是 Angular2 及以上的版本。而 Angular 与 TypeScript 的完美结合,对于一个 .NET 开发者来说,实在是找不到不用它的理由了,更多的优势来不及说了,快上车吧。

使用 angular-cli 初始化项目

Angular CLI 是一个用于构建 Angular 项目的命令行界面工具,它可以创建项目、添加文件以及执行一大堆开发任务,比如测试、打包和发布。

设置开发环境

在开始工作之前,我们必须设置好开发环境。

如果你的机器上还没有 Node.js®和npm,请先安装它们。

请先在终端/控制台窗口中运行命令 node -vnpm -v, 来验证一下你正在运行 node 6.9.x 和 npm 3.x.x 以上的版本。 更老的版本可能会出现错误,最新的版本则没问题。

安装 angular-cli

@H_301_25@npm install -g @angular/cli@latest

查看 cli 命令

@H_301_25@ng help

生成项目模版

@H_301_25@ng new zero-admin-web --style=scss cd zero-admin-web ng server --运行

生成模版时常用的一些参数:

  • --style=scss 指定使用scss,默认使用css
  • --routing=false 是否生成一个路由模块
  • --inline-style=false 是否使用内联样式
  • --inline-template=false 是否使用内联模版

启动开发服务器

进入项目目录,并启动开发服务器

@H_301_25@cd zero-admin-web ng serve --open

默认端口是4200,在浏览器中打开 http://localhost:4200 ,便能看到页面成功加载,并显示 “Welcome to app!”。

并且 ng serve 命令会启动文件的监控,当你修改这些文件时将自动重新编译,并刷新浏览器。而 --open 参数则表示是否自动打开浏览器。

生成发布包

@H_301_25@ng build --prod

build 用来生成压缩,优化后的JS,用来部署到生产环境,默认放成在 dist 文件夹下, --prod 用来指定发布环境。

angular-cli常用指令

可以使用ng generate 或者简写形式 ng g 命令来生成Angular组件:

@H_301_25@ng generate component my-component1 #生成一个名称为my-component1的组件

使用 ng generate 命令时,会相对于 src/app/ 目录来生成组件,可以在生成的时候指定多级目录。
当然,也支持生成指令,管道,服务,类,接口,模块等,如下所示:

脚手架 用法
Component ng g component my-new-component
Directive ng g directive my-new-directive
Pipe ng g pipe my-new-pipe
Service ng g service my-new-service
Class ng g class my-new-class
Guard ng g guard my-new-guard
Interface ng g interface my-new-interface
Enum ng g enum my-new-enum
Module ng g module my-module

项目结构

先看看项目模版里的文件结构,以及他们都是做什么的:

┌── e2e
│   ├── app.e2e-spec.ts
│   ├── app.po.ts
│   └── tsconfig.e2e.json
├── src
│   ├── app
│   │   ├── app.component.css
│   │   ├── app.component.html
│   │   ├── app.component.spec.ts
│   │   ├── app.component.ts
│   │   └── app.module.ts
│   ├── assets
│   │   └── .gitkeep
│   ├── environments
│   │   ├── environment.prod.ts
│   │   └── environment.ts
│   ├── favicon.ico
│   ├── index.html
│   ├── main.ts
│   ├── polyfills.ts
│   ├── styles.css
│   ├── test.ts
│   ├── tsconfig.app.json
│   ├── tsconfig.spec.json
│   └── typings.d.ts
├── .angular-cli.json
├── .editorconfig
├── .gitignore
├── karma.conf.js
├── package.json
├── protractor.conf.js
├── README.md
├── tsconfig.json
└── tslint.json

e2e/

e2e/ 目录中的是端到端(End-to-End)测试代码。 它们不在 src/ 下,是因为端到端测试实际上和应用是相互独立的,它只适用于测试我们的应用,这也是为什么它会拥有自己的 tsconfig.e2e.json 文件的原因。

src/

我们的应用代码位于 src 文件夹中。 所有的 Angular组件、模板、样式、图片以及应用所需的任何东西都在这个目录下, 这个目录之外的文件都是为构建应用提供支持用的。

package.json

这是项目的基本定义文件,所有的基于nodejs的项目都会有一个package.json文件,里面会定义项目名称、版本、依赖的库,以及脚本。

.angular-cli.json

Angular CLI 的配置文件。 在这个文件中,可以设置一系列默认值,还可以配置项目编译时要包含哪些文件等。

karma.conf.js

Karma 的单元测试配置,当运行 ng test 时会用到它。

protractor.conf.js

给*Protractor** 使用的端到端测试配置文件,当运行 ng e2e 的时候会用到它。

tsconfig.json

TypeScript 编译器的配置,IDE会借助它来为我们提供更好的代码提示,语法检查等。

tslint.json

TSLintcodelyzer 用的配置信息,当运行 ng lint 时会用到。 Lint功能可以帮我们保持代码风格的统一。

Angular Material

Material Design,中文名:材料设计语言,是由Google推出的全新的设计语言,谷歌表示,这种设计语言旨在为手机、平板电脑、台式机和“其他平台”提供更一致、更广泛的“外观和感觉”。

据谷歌介绍,Material Design基于“真实的触感,灵感源自对纸和墨水的研究,” 能够让用户 “理解那些用于替代真实世界的可视线索”,“而又不违背力学原理”。另外,光线、表面和移动的基本原理是表现对象如何移动、交互和相互关联地存在于空间中的关键。逼真的光影效果可以显示区块间的接缝、划分空间、以及标识移动的部件。更多详细的介绍可以看 Material 的官网 https://material.io。

而 Angular Material 则是由 Angular 团队完全基于 Material 规范,完美实现的一套 Angular2+ UI框架。

安装配置步骤

第一步:安装

使用 npm 安装 Angular Materil 和 Angular CDK

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

注: CDK是(Component Dev Kit)的缩写,Angular 的组件开发包,用于分离组件开发与 Material 的耦合(目前大多还耦合在一起),以方便使用其它风格的设计来开发组件。

第二步:动画

有一些 Angular Material 组件依赖于 Angular 动画模块,以便能进行一些高级的 transitions。如果你希望使用这些动画,则需要安装 @angular/animations 模块。

@H_301_25@npm install --save @angular/animations

导入动画模块

import {browserAnimationsModule} from '@angular/platform-browser/animations';

@NgModule({
  ...
  imports: [browserAnimationsModule],...
})
export class AppModule { }

第三步:导入

导入你想要使用的 Angular Material 模块

import {MdButtonModule,MdCheckBoxModule} from '@angular/material';

@NgModule({
  ...
  imports: [MdButtonModule,MdCheckBoxModule],...
})
export class AppModule { }

第四步:主题

定制一个主题,所有的组件都将遵循于这个主题。Angular Material 内置了几种主题,我们可以在 style.css 文件中导入:

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

更多主题的介绍以及如何自定义主题,则可以参考 theming guide。

第五步:手势

有些组件,如(md-slide-toggel,md-slider,mdTooltip)等依赖于 HammerJS 而支持手续操作。所以,如果你需要在你的项目中实现手势操作,则需要装 HammerJS 加载进来。

使用 npm 安装:

@H_301_25@npm install --save hammerjs

导入到根模块中:

import 'hammerjs';

第六步:图标

如果你想通过 md-icon 组件来使用经典的 Material Design Icons 图标字体,则需要把 material-icons 的字体样式加载进来。

添加 material-icons.css

@font-face {
  font-family: 'Material Icons';
  font-style: normal;
  font-weight: 400;
  src: local('Material Icons'),local('MaterialIcons-Regular'),url(../fonts/MaterialIcons-Regular.woff2) format('woff2'),/* Super Modern browsers */
    url(../fonts/MaterialIcons-Regular.woff) format('woff'),/* Super Modern browsers */
    url(../fonts/MaterialIcons-Regular.ttf) format('truetype'),/* Safari,Android,iOS */
    url(../fonts/MaterialIcons-Regular.svg) format('svg'); /* Legacy iOS */
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: Nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

/* Rules for sizing the icon. */
.material-icons.md-18 { font-size: 18px; }
.material-icons.md-24 { font-size: 24px; }
.material-icons.md-36 { font-size: 36px; }
.material-icons.md-48 { font-size: 48px; }

/* Rules for using icons as black on a light background. */
.material-icons.md-dark { color: rgba(0,0,0.54); }
.material-icons.md-dark.md-inactive { color: rgba(0,0.26); }

/* Rules for using icons as white on a dark background. */
.material-icons.md-light { color: rgba(255,255,1); }
.material-icons.md-light.md-inactive { color: rgba(255,0.3); }

然后在 index.html 中引用 material-icons.css

<!-- Icons -->
<link href="assets/css/material-icons.css" rel="stylesheet">

字体文件下载地址为:material-design-icons。

不过更加推荐的是直接使用 Google 提供的 CDN 服务(现在国内访问速度非常快),只需要在 index.html 中添加如下引用即可:

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

总结

本文简单描述了如何使用 angular-cli 初始化项目和 material2 UI框架的配置,比起 webpack 那一大堆配置,angular-cli 则要简洁的多,而 angular-cli 生成的那么多文件,对于新手来说,可能有些还是不太理解,这个在后续会慢慢介绍,不要着急,前期不应过于执着细节,而是要先愉快的跑起来。而下一章则会介绍一下Angular项目的持续集成。

关于notes:Get Started with Angular的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于5ThingsToKnowBeforeYouGetStartedWithAngulerJS、Angular Starter Kit —— Angular 2.0 迁移准备工具 (TypeScript)、Angular 学习笔记 (Angular 12 get started)、Angular 小试牛刀[1]-Getting Started的相关信息,请在本站寻找。

本文标签: