2020-07-21

核心知識:模塊、組件、模板、指令、數(shù)據(jù)綁定、服務(wù)和依賴注入、路由

一、模塊

(ng 中,模塊指的是項目中功能模塊,是一個抽象的概念,把功能劃分出來,如商品模塊,用戶模塊等。)

NG 中的模塊叫做 NgModule,與 ES 和 node.js 中‘模塊’概念不同。

ES 和 node.js 模塊,一個文件就是一個模塊,可以導出內(nèi)部成員,引用其他模塊的成員。NG 中的模塊指項目中的 功能模塊。

主組件的作用

引導加載模塊的流程

二、組件

(組件是一塊可重復使用的頁面區(qū)域,有專有的樣式、模塊、數(shù)據(jù),表現(xiàn)上就是一個自定義標簽)

在 login.ts 文件中

  1. 導入核心,為了能夠使用裝飾器
import {Component} from '@angular/core'
  1. 導出組件對象
export class Login{ }
  1. 寫裝飾器
@Component({  //裝飾器,相當于給Login貼上工牌   
  selector:'my-login',   
  template:'<h3>我的第一個angular組件</h3><br>'
 })
// 上面的代碼都是描述Login這個組件的數(shù)據(jù),那么上面每個數(shù)據(jù)都叫做元數(shù)據(jù)

在 app.Module.ts 中

  1. 組件必須去主模塊聲明一下 app.Module.ts

    4.1 導入子組件

import { Login } from './login';
4.2 注冊
@NgModule({    
  declarations: [        
    AppComponent,        
    Login    
  ],    ... })

在 app.component.html 中

5.使用自定義組件 app.component.html 中

<my-login></my-login>

三、數(shù)據(jù)綁定

angular 數(shù)據(jù)綁定

VueJS 數(shù)據(jù)綁定

m--v: 插值表達式

{{}}

{{}}

m--v: 屬性綁定

[src]=

v-bind: :src

v--m: 事件綁定

(click)

v-on @click='delect'

雙向綁定

[(value)]

v-model:value

數(shù)據(jù)綁定

import {Component} from '@angular/core'
@Component({
    selector:'emp-info',
    template:`
       <h3>員工信息</h3> 
       <div>員工姓名:{{emp.ename}}</div>
       <div>員工姓名:{{emp.ename.toUpperCase()}}</div>
       <div>員工姓名:{{emp.ename.toUpperCase().slice(2)}}</div>
       <div>員工薪資:{{'¥'+emp.salary*12}}</div>
       <div>員工性別:{{emp.gender==1 ? '男':'女'}}</div>
       <div>員工生日:{{emp.birthdate}}</div>
       <div>員工項目:{{emp.projectList}}</div>
       <ul>
           <li>{{emp.projectList[0]}}</li>
           <li>{{emp.projectList[1]}}</li>
           <li>{{emp.projectList[2]}}</li>
       </ul>
       // <div>{{emp}}</div>
       // vuejs 中這種寫法,會自動轉(zhuǎn)換成 json 字符串
       // ng 不能自動轉(zhuǎn) ng 是 [Object Object] 
  
      // <div>{{JSON.stringify(emp)}}</div>
      // <div>{{new Date(emp.birthdate).getFullYear())}}</div>
      // <div>{{parseInt(123.456))}}</div>
      // 插值表達式中不能使用任何全局對象
    `
})
?
export class EmpInfo{
    num = 12.5;
    emp={
        ename:'lilei',
        gender:1,
        salary:10000,
        birthdate:1501234567890,
        projectList:['項目1','項目2','項目3']
    };
    showInfo() {
        console.log('調(diào)用了showInfo()');
        return '123';
    }
}

重點知識:

{{}}插值表達式,與vuejs的不通用

  1. 不能使用關(guān)鍵字new new Date

  2. 不能使用全局函數(shù) parseInt

  3. 不能使用全局對象 window、json

四、指令

Vuejs 提供13個指令

v-for、v-if、v-else-if、v-else、v-show

v-bind:/:、v-on:/@

v-html、v-text、v-cloak

v-once v-pre

v-model

angular中的指令分為三類(common 自動導包、forms 和 router 自行導包)

  1. 組件就是一種特殊的指令:NG中組件繼承自指令,組件是一種特殊的指令

Component extends Direvtive

  1. 結(jié)構(gòu)型指令,影響dom樹結(jié)構(gòu)的指令,必須以*號開頭

ngFor 、ngIf 、ngSwitchCase、ngSwitchDefault

  1. 屬性型指令,會影響dom元素的屬性值 (類似:bind),必須使用[ ]括起來

[ngClass] [ngStyle] [ngSwitch] [(ngModel)]

  1. *ngFor:對數(shù)組或者對象進行遍歷。使用這個指令,自動生成一個 index 也就是下標值
// html
<button (click)="addScore()">給數(shù)據(jù)添加隨機數(shù)</button>
<h3>遍歷數(shù)組</h3>
<ul>
  <li *ngFor="let score of scores;let i=index">
    {{score}}--{{i}}
  </li>
</ul>
?
// component.ts
scores = [89, 91, 71];
addScore() {
    const num = Math.floor(Math.random() * 100);
    this.scores.push(num);
}
=======================================================================
// html
<h3>刪除數(shù)據(jù)</h3>
<table>
  <thead>
    <tr>
      <th>編號</th>
      <th>姓名</th>
      <th>性別</th>
      <th>操作</th>
    </tr>
    <tr *ngFor="let e of elist">
      <td> {{e.eid}} </td>
      <td> {{e.ename}} </td>
      <td> {{e.gender==1?'男':'女'}} </td>
      <td>
          <button (click)="delete(i)">刪除</button>
      </td>
    </tr>
  </thead>
</table>
?
// component.ts
elist = [
    { eid: 101, ename: 'dingding', gender: 1 },
    { eid: 102, ename: 'tuangtuang', gender: 0 },
    { eid: 103, ename: 'biangbiang', gender: 1 },
  ];
?
  delete(index) {
    this.elist.splice(index, 1);
  }
  1. *ngIf:true 則掛載指定元素,false 刪除指定元素
// html
<button (click)="isShow=!isShow">顯示與隱藏</button>
<ng-container *ngIf="isShow; else noShow">
    顯示
</ng-container>
<ng-template #noShow>
    隱藏
</ng-template>
// component.ts
isShow=true;
  1. ngSwitch:實現(xiàn)多條件判定

傳統(tǒng)switch

var status=10;switch(status){
  case 10:   ...
   break;
  case 20:   ...
   break;
  default:
    ...}

ngSwitch——屬性指令 [ngSwitch]=10

ngSwitchCase——結(jié)構(gòu)指令 *ngSwitchCase=10

ngSwitchDefault——結(jié)構(gòu)指令 *ngSwitchDefault

面試會問 ngSwitch 是什么指令?

<div [ngSwitch]="status">
    <p *ngSwitchCase="1">
        等待...
    </p>
    <p *ngSwitchCase="2">
        完結(jié)...
    </p>
    <p *ngSwitchDefault>
        走起...
    </p>
</div>
status=1;
  1. ngStyle 和 ngClass
import { Component } from "@angular/core";
 
@Component({
  selector:'style-class-demo',
  // 使用css屬性選擇器要要引入css文件
  styleUrls:['../assets/css/bgcolor.css'],
  template:`
  <h3>ngStyle和ngClass的演示</h3>
  <p [ngStyle]='{"background-color":"#006699"}'>第一段話</p>
  <p [ngStyle]='styleObj'>第二段話</p>
  <div [ngClass]='classObj'>class</div>`
})
export class StyleClassDemo{
  styleObj={
    'background-color':'#990066',
    'color':'#fff'  
  };
   classObj={'bgcolor':true};
 }

注意:

使用 NgClass 需要在 @Component 中引用寫好的 css 樣式

styleUlrs: ['../assets/css/*.css']

其實,搞個全局 css 文件就行,其他筆記中會介紹 css 文件的引用方式。

  1. 自定義指令
import {  Directive, ElementRef } from "@angular/core";
?
@Directive({
  //定義使用指令時的名稱
  selector:'[xzFocus]'
})
export class xzFocus{
  // 指令的真正作用---構(gòu)造函數(shù)
  // 如何獲取當前的 dom 節(jié)點對象 el:ElementRef 
  // 只能獲得當前元素對象,無法獲得當前元素
  constructor(el:ElementRef){
    // el.nativeElement 才是真正的 dom 樹上的對象
    console.log(el.nativeElement);
    // 哪一個元素獲取焦點
    el.nativeElement.focus()
}

總結(jié):

  1. 裝飾器是 @Directive

  2. 裝飾器中的 selector:'[xzFocus]'

  3. 注冊與 component 一樣

  4. 使用 <input xzFocus>

  5. 在對象的構(gòu)造函數(shù)中,寫真正的指令作用代碼

  6. 如果獲取當前使用指令的 dom 對象

    通過參數(shù) el:ElementRef(ElementRef 需要引用)

    el.nativeElement ---> 才是使用指令的 dom 對象

  1. 雙向綁定 [(ngModel)]

使用ngModel的步驟

1.導入包@angular/Forms中的{ FormsModule }

2.在模塊中的imports屬性中注冊這個對象,才能使用

3.使用雙向綁定 [(ngModel)]='kw'

import { Component } from "@angular/core";
 
@Component({
    selector:'ngmodel-demo',
    template:`
        <h3>雙向綁定的演示</h3>
        <input type="text" [(ngModel)]='kw'>
        <p>{{ kw }}</p>`
})
export class NGModelDemo{
    // 雙向綁定找不到數(shù)據(jù)了
    // view中kw
    innerkw='Dell';
    get kw(){
        console.log('get kw');
        return this.innerkw;
    }
    // 只要有人想改變 kw,set 會自動調(diào)用
    set kw(val){
        console.log('set kw');
        this.innerkw = val;
        //此處可以根據(jù)用戶的輸入執(zhí)行 XHR 的異步請求
    }
}
練習:模擬百度搜索自動聯(lián)想
VueJS 中
new Vue({
    data(){
        return { kw=''}
        },
     watch{ 
         kw:function()}
         }
});

Angular 中,使用set/get方法,對數(shù)據(jù)進行監(jiān)聽

import { Component } from "@angular/core";
 
@Component({
  selector:'ngmodel-demo',
  template:`
    <h3>雙向綁定的演示</h3>
    <input type="text" [(ngModel)]='kw'>
    <p>{{kw}}</p>
  `
})//55下課 ,10點07上課
export class NGModelDemo{
  //雙向綁定找不到數(shù)據(jù)了
  //view中kw
  innerkw='Dell';
  get kw(){
    console.log('get kw');
    return this.innerkw;
  }
  //只要有人想改變KW,set會自動調(diào)用
  set kw(val){
    console.log('set kw');
    this.innerkw=val;
    //此處可以根據(jù)用戶的輸入執(zhí)行XHR的異步請求
  }
}

?

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容