Angular -- Basics

What is Angular

Angular is a UI binding framework that binds the View (HTML) with View Model (Typescript) -- Uses MVVM pattern.

Angular also allows you to build SPA (single page application) with routing and built in HTTP & DI support

Angular JS vs. Angular

  • Version: 1.x (Angular JS) vs. 2+ (Angular)
  • Language: Javascript (Angular JS) vs. Typescript (Angular)
  • Pattern: MVC (Angular JS) vs. MVVM (Angular)
  • Mobile support: No (Angular JS) vs. Yes (Angular)

MV-(X) Patterns

All of these patterns separate the responsibilities of visualizing, processing, and data management for UI applications. And the use of these patterns increases --

  • Modularity
  • Flexibility
  • Testability
  • Maintainability

MVC

单向互动: View ---event--> Controller ---new data--> Model --send data--> View

  • Model: The database, where data object is stored and sent to view

  • Controller: business logic of the application. It gets the event from view, process that by applying business logic & rules, and update the model.

  • View — this component has two important tasks: presenting data to the user and handling user interaction. It sends the user event to controller.

MVP

与MVC的区别:双向 + V/M分离

1. 各部分之间的通信,都是双向

2. View 与 Model 不发生联系,都通过 Presenter 传递。

3. View 非常薄,不部署任何业务逻辑,称为"被动视图"(Passive View),即没有任何主动性,而 Presenter非常厚,所有逻辑都部署在那里

MVVM

与MVC的区别:双向 + V/M分离 + Data Binding

1. 各部分之间的通信,都是双向

2. View 与 Model 不发生联系,都通过 ViewModel 传递

3. 采用双向绑定(data-binding):View的变动,自动反映在 ViewModel,反之亦然。Angular 和 Ember 都采用这种模式

Compilation

Angular provides two types of compilation:

  • JIT(Just-in-Time) compilation
  • AOT(Ahead-of-Time) compilation

JIT: compiles inside the browser during runtime. (ng build; ng serve)
AOT: during the build time. (ng build --aot; ng serve --aot) Advantage

  • faster rendering
  • fewer ajax requests for source files such as HTML and CSS
  • minimizing errors -- by resolving them at compiletime
  • better security

Components

Components are the basic building blocks, which control a part of the UI for any application.

  • Component defines view
  • Contains application data and logic
  • Is combined with an HTML template
  • Components make changes to the template before display
  • Angular app has 1 root component:
    • it connects the component hierarchy to a template (DOM)

A component is a TS class which angular depend upon to create objects. You can build your own declarative components into bite-sized, reusable pieces.

Each component is defined by @Component decorator

e.g. ng generate component <component name>

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

      @Component({
        selector: 'app-test',
        templateUrl: './test.component.html',
        styleUrls: ['./test.component.css'],
        providers:  [ HeroService ]
      })
      export lass TestComponent implements OnInit {

        constructor() {}

        ngOnInit() {
        }
      }
  • selector: the "name" of the component that we refer to in the template
  • templateUrl: the module-relative url of the HTML template, i.e. the host HTML, you also have the option to provide inline HTML
  • styleUrls: array of module-relative url of the CSS stylesheets, you also have the option to provide inline CSS styles
  • providers: array of service providers
  • ** Components can have nested view hierarchy, lower level views can be imported from other modules

Service 

  • Objects instantiated only once during the lifetime of an application
  • The main objective of a service is to share data, functions with different components of an Angular application.
  • Every module is defined with a @Injectable decorator.
  • ng g s <service name> 

      import { Injectable } from '@angular/core';

      @Injectable({
        providedIn: 'root'
      })
      export class TestServiceService {

        constructor() { }

      }

Data binding

Data binding allows you to move your data from the JS code to the view, without having to write the glue code yourself.

Dependency injection

Modular services can be created and be injected anywhere you want, improves testability and reusability.

Angular CLI

Command-line interface (CLI) tool to make it easier to bootstrap and develop your Angular applications

Bootstrap new application

ng new my-app

** to use the default set-up, keep hitting enter

What it does?

  • Basically, it creates a new workspace and with app skeletons and end-to-end tests.

Run the app: 

  • In development mode: CLI compiles the changes as it happens and refreshes our UI 
ng serve -o

  ** -o option automatically opens your browser to http://localhost:4200/.

  • In production mode: CLI creates an optimal compiled build, served via static files

Angular Structure

  • A very concise view of the app skeleton, NOT complete!

Root level

Workspace config files

package.json vs. package-lock.json

  • package-lock.json:

    • auto-generated.

    • Records the exact version of each installed package

    • Purporse is to make sure future installs to have the exact same versions.

  • package.json:

    • Records the package info (not just the version) currently installed.

Root application config files:

angular.json

  • Under "projects":  

src/

Index.html

  • Root HTML -- responsible for deciding which files are to be loaded
  • Clean and pristine -- no references to any scripts or dependencies
  • <app-root> element in the HTML, which is the marker for loading our application code
    • Loading is done by ng-serve command -- combines all the vendor libraries, our application code, the styles, and inline templates into bundles, then inject dynamically into root HTML when page is loaded.

main.ts

  • Entry point -- which Angluar module will be loaded when the app starts
  • Points the Angular framework at the core module of your application and let it trigger the rest of your application source code from that point.

app.module.ts

  • Main module: application-specific source code starts from here, containing the core configuration of your application --
    • Loading dependencies
    • Declaring components
    • Marking the location of the main entry point component
  • Declare Angular modules starts with: 
@NgModule({  
  • Declare components within the NgModule:
declarations: [AppComponent],
  • Import other dependency modules within the NgModule:
providers: [],
  • Declare entry point component within the NgModule:
bootstrap: [AppComponent]

app/

NgComponent

The component .ts file

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

@Component({
  selector: 'app-stock-item',
  templateUrl: './stock-item.component.html',
  styleUrls: ['./stock-item.component.css']
})
export class StockItemComponent implements OnInit {  1

  public name: string;                        2
  public code: string;
  public price: number;
  public previousPrice: number;

  constructor() { }

  ngOnInit() {                                3
    this.name = 'Test Stock Company';         4
    this.code = 'TSC';
    this.price = 85;
    this.previousPrice = 80;
  }
}
  • OnInit: interface used as a hook to when the component is initialized, after all the data fields are initialized. 
  • ngOnInit: function that run when component is initialized, where you write your initialization logic

To use the component, include selector in the app.component.html file 

<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <app-stock-item></app-stock-item>
</div>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值