10分鐘快速上手angular cdk

楊明明發表於2018-04-07

coercion 常用型別轉換工具

@angular/cdk/coercion 常用型別轉換工具

import { Component, OnInit } from "@angular/core";
import {
  coerceArray,
  coerceBooleanProperty,
  coerceNumberProperty,
  _isNumberValue
} from "@angular/cdk/coercion";
@Component({
  selector: "coercion",
  templateUrl: "./coercion.component.html",
  styleUrls: ["./coercion.component.scss"]
})
export class CoercionComponent implements OnInit {
  constructor() {}

  ngOnInit() {
    let a = 1;
    // 轉化為array
    let aa = coerceArray(a);
    console.log(aa);
    // 轉化為boolean
    let b = coerceBooleanProperty("true");
    console.log(b);
    // 轉化為number
    let c = coerceNumberProperty("10.0");
    console.log(c);

    // 判斷是否number
    let isNum = _isNumberValue('d');
    console.log(isNum);
  }
}
複製程式碼

layout 響應式佈局工具

@angular/cdk/layout 響應式佈局工具

  • Breakpoints 螢幕尺寸
  • BreakpointObserver 觀察器
  • MediaMatcher 媒體查詢匹配
import { Component, OnInit } from "@angular/core";
import {
  BreakpointObserver,
  BreakpointState,
  MediaMatcher,
  Breakpoints
} from "@angular/cdk/layout";
import { Observable } from "rxjs/Observable";
@Component({
  selector: "layout",
  templateUrl: "./layout.component.html",
  styleUrls: ["./layout.component.scss"]
})
export class LayoutComponent implements OnInit {
  isHandset: Observable<BreakpointState>;
  constructor(public bm: BreakpointObserver, public media: MediaMatcher) {}

  ngOnInit() {
    // 手持裝置
    let Handset = Breakpoints.Handset;
    // 手持landscape屏
    let HandsetLandscape = Breakpoints.HandsetLandscape;
    //手持portrait屏
    let HandsetPortrait = Breakpoints.HandsetPortrait;
    // 多媒體
    let Medium = Breakpoints.Medium;
    // 平板電腦
    let Tablet = Breakpoints.Tablet;
    // 平板電腦 Landscape
    let TabletLandscape = Breakpoints.TabletLandscape;
    // 平板電腦 Portrait
    let TabletPortrait = Breakpoints.TabletPortrait;
    // web
    let Web = Breakpoints.Web;
    // web landscape
    let WebLandscape = Breakpoints.WebLandscape;
    // web portrait
    let WebPortrait = Breakpoints.WebPortrait;
    // 大螢幕
    let Large = Breakpoints.Large;
    // 更大螢幕
    let XLarge = Breakpoints.XLarge;
    // 更小螢幕
    let XSmall = Breakpoints.XSmall;
    // 小螢幕
    let Small = Breakpoints.Small;

    let isSmall = this.media.matchMedia(Small);
    console.log("is small matcher", isSmall);
    console.log("is small", this.bm.isMatched(Small));

    let isXSmall = this.media.matchMedia(XSmall);
    console.log("is xsmall matcher", isXSmall);
    console.log("is xsmall", this.bm.isMatched(XSmall));

    // 是否滿足多個條件
    this.bm
      .observe([
        Handset,
        HandsetLandscape,
        Handset,
        Medium,
        Tablet,
        TabletLandscape,
        TabletPortrait,
        Web,
        WebLandscape,
        WebPortrait,
        Large,
        XLarge,
        Small,
        XSmall
      ])
      .subscribe(res => {
        console.log(res);
      });
  }
}
複製程式碼

keycodes 常用鍵碼

@angular/cdk/keycodes 常用鍵碼

export const UP_ARROW = 38;
export const DOWN_ARROW = 40;
export const RIGHT_ARROW = 39;
export const LEFT_ARROW = 37;
export const PAGE_UP = 33;
export const PAGE_DOWN = 34;
export const HOME = 36;
export const END = 35;
export const ENTER = 13;
export const SPACE = 32;
export const TAB = 9;
export const ESCAPE = 27;
export const BACKSPACE = 8;
export const DELETE = 46;
export const A = 65;
export const Z = 90;
export const ZERO = 48;
export const NINE = 57;
export const NUMPAD_ZERO = 96;
export const NUMPAD_NINE = 105;
export const COMMA = 188;
複製程式碼

bidi 佈局方向

@angular/cdk/bidi 佈局方向

  • Directionality
  • Direction
  • DIR_DOCUMENT
  • Dir
  • BidiModule
<!--從左到右-->
<p dir="LTR">
  bidi works!
</p>
<!--從右到左-->
<p dir="RTL">
  bidi works!
</p>
<!--可以控制方向-->
<p [dir]="dir">
  bidi works!
</p>

<a href="javascript:;" (click)="switchDir()">改變</a>

複製程式碼
import { Component, OnInit, Inject } from "@angular/core";
import { DIR_DOCUMENT, Directionality } from "@angular/cdk/bidi";
@Component({
  selector: "bidi",
  templateUrl: "./bidi.component.html",
  styleUrls: ["./bidi.component.scss"]
})
export class BidiComponent implements OnInit {
  dir: string = "rtl";
  constructor(
    @Inject(DIR_DOCUMENT) public dirDoc: any,
    public directionlity: Directionality
  ) {}

  ngOnInit() {
    // 獲取document
    console.log(this.dirDoc);
    // ltr 獲取當前值
    let dir = this.directionlity.value;
    console.log("dir is ", dir);
  }

  switchDir() {
    if (this.dir === "rtl") {
      this.dir = "ltr";
    } else {
      this.dir = "rtl";
    }
  }
}

複製程式碼

platform 當前平臺

@angular/cdk/platform 當前平臺

  • supportsPassiveEventListeners 是否支援被動監聽
  • getSupportedInputTypes 支援輸入的型別
  • Platform 服務
import { Component, OnInit } from "@angular/core";
import {
  Platform,
  supportsPassiveEventListeners,
  getSupportedInputTypes
} from "@angular/cdk/platform";
@Component({
  selector: "platform",
  templateUrl: "./platform.component.html",
  styleUrls: ["./platform.component.scss"]
})
export class PlatformComponent implements OnInit {
  constructor(public plat: Platform) {}

  ngOnInit() {
    // 是否支援被動監聽
    let isSupportsPassiveEventListeners = supportsPassiveEventListeners();
    console.log(
      "isSupportsPassiveEventListeners",
      isSupportsPassiveEventListeners
    );
    // 支援輸入的型別
    let supportedInputTypes = getSupportedInputTypes();
    console.log("supportedInputTypes", supportedInputTypes);
    // 是否安卓
    let ANDROID = this.plat.ANDROID;
    // 是否IOS
    let IOS = this.plat.IOS;
    // 是否BLINK引擎
    let BLINK = this.plat.BLINK;
    // 是否DEGE瀏覽器
    let EDGE = this.plat.EDGE;
    // 是否FIREFOX瀏覽器
    let FIREFOX = this.plat.FIREFOX;
    // 是否SAFARI
    let SAFARI = this.plat.SAFARI;
    // 是否TRIDENT
    let TRIDENT = this.plat.TRIDENT;
    // 是否WEBKIT
    let WEBKIT = this.plat.WEBKIT;
    // 是否瀏覽器
    let isBrowser = this.plat.isBrowser;
  }
}
複製程式碼

portal 動態內容呈現

@angular/cdk/portal 動態內容呈現

CdkPortal

[cdk-portal], [cdkPortal], [portal]

CdkPortalOutlet

[cdkPortalOutlet], [cdkPortalHost], [portalHost]

<h2 class="title">
  我是component</h2>
<ng-template #portalComponentOutlet cdkPortalOutlet></ng-template>

<h2 class="title">我是template</h2>
<ng-template #portalTemplateOutlet cdkPortalOutlet></ng-template>


<h2 class="title">我是會變得</h2>
<ng-template [cdkPortalOutlet]="greeting"></ng-template>

<h2 class="title">我是自動獲取的</h2>
<ng-template [cdkPortalOutlet]="myCdkPortal2"></ng-template>

<ng-template cdkPortal #myCdkPortal>
  我是自動獲取的,我是自動獲取的
</ng-template>

<ng-template #tpl>
  ng template portal
</ng-template>
複製程式碼
import {
  Component,
  OnInit,
  ViewChild,
  TemplateRef,
  ViewContainerRef
} from "@angular/core";
import {
  CdkPortalOutlet,
  ComponentPortal,
  TemplatePortal,
  CdkPortal
} from "@angular/cdk/portal";
import { PortalCompComponent } from "./portal-comp/portal-comp.component";
@Component({
  selector: "app-portal",
  templateUrl: "./portal.component.html",
  styleUrls: ["./portal.component.scss"]
})
export class PortalComponent implements OnInit {
  greeting: any;
  @ViewChild("portalComponentOutlet", { read: CdkPortalOutlet })
  portalComponentOutlet: CdkPortalOutlet;

  @ViewChild("portalTemplateOutlet", { read: CdkPortalOutlet })
  portalTemplateOutlet: CdkPortalOutlet;

  @ViewChild("myCdkPortal", { read: CdkPortal })
  myCdkPortal2: CdkPortal;

  @ViewChild("tpl") tpl: TemplateRef<any>;

  constructor(public view: ViewContainerRef) {}

  ngOnInit() {
    console.log(this.myCdkPortal2);
    let componentPortal = new ComponentPortal(PortalCompComponent);
    let templatePortal = new TemplatePortal(this.tpl, this.view);

    // attach後不可變
    this.portalComponentOutlet.attach(componentPortal);
    // attach後不可變
    this.portalTemplateOutlet.attach(templatePortal);

    // 可以檢測自動變更 推薦
    this.greeting = componentPortal;
    setInterval(() => {
      if (this.greeting === templatePortal) {
        this.greeting = componentPortal;
      } else {
        this.greeting = templatePortal;
      }
    }, 1000);
  }
}
複製程式碼

scrolling 滾動

@angular/cdk/scrolling 對滾動事件做出響應的工具包

ScrollDispatcher 滾動排程器

滾動排程器

@ViewChild("scrollAble", { read: CdkScrollable })
  scrollAble: CdkScrollable;

  @ViewChild("scrollAble2") scrollable2: ElementRef;
  constructor(
    public scrollDispatcher: ScrollDispatcher,
    public ele: ElementRef
  ) {}

  ngOnInit() {}

  ngAfterViewInit() {
    // 獲取所有cdkScrollable
    const scrollContainers = this.scrollDispatcher.scrollContainers;
    console.log("scrollContainers", scrollContainers);
    // 登出一個cdkScrollable
    this.scrollDispatcher.deregister(this.scrollAble);
    // 註冊一個cdkScrollable
    this.scrollDispatcher.register(this.scrollAble);

    // 獲取上級滾動容器
    let elementRef = this.scrollAble.getElementRef();
    let ancestorScrollContainers = this.scrollDispatcher.getAncestorScrollContainers(
      elementRef
    );
    let ancestorScrollContainers2 = this.scrollDispatcher.getAncestorScrollContainers(
      this.scrollable2
    );
    console.log("ancestorScrollContainers", ancestorScrollContainers);
    console.log("ancestorScrollContainers2", ancestorScrollContainers2);
    // 滾動監聽
    this.scrollDispatcher.scrolled().subscribe(res => {
      console.log(res);
    });
  }
複製程式碼

CdkScrollable 可滾動指令

用於註冊可滾動元素

@ViewChild("scrollAble", { read: CdkScrollable })
scrollAble: CdkScrollable;

constructor(public scrollDispatcher: ScrollDispatcher) {}

ngOnInit() {}

ngAfterViewInit() {
    // 元素是否滾動了
    this.scrollAble.elementScrolled().subscribe(res => {
      console.log("scroll able scrolling", res);
    });
    // 獲取scroll able 的 ElementRef
    let scrollable1ElementRef = this.scrollAble.getElementRef();
    console.log("scroll able element ref", scrollable1ElementRef);
}
複製程式碼

ViewportRuler 視口

// 注入視口尺寸服務
constructor(public viewPort: ViewportRuler) {}

ngOnInit() {
    // 監控視口變化
    this.viewPort.change().subscribe(res => {
      this.getViewPortInfo();
    });
    this.getViewPortInfo();
}
// 獲取視口資訊
getViewPortInfo(){
    let viewRect = this.viewPort.getViewportRect();
    console.log("view rect", viewRect);
    let viewPortScrollPosition = this.viewPort.getViewportScrollPosition();
    console.log("viewPortScrollPosition", viewPortScrollPosition);
    let viewPortSize = this.viewPort.getViewportSize();
    console.log("viewPortSize", viewPortSize);
}
複製程式碼

observers 監聽dom變化

@angular/cdk/observers 監聽dom變化

  • @Input() debounce: number 發射時間間隔
  • @Input('cdkObserveContentDisabled') disabled: any 可用開關
  • @Output('cdkObserveContent') event: new EventEmitter<MutationRecord[]>() 內容更改觸發

案例

<div class="projected-content-wrapper" (cdkObserveContent)="projectContentChanged()">
  <ng-content></ng-content>
</div>
複製程式碼

定位策略

PositionStrategy

滾動策略

ScrollStrategy

塊滾動策略

BlockScrollStrategy

空的滾動策略

NoopScrollStrategy

關閉滾動策略

CloseScrollStrategy

關閉滾動策略配置

CloseScrollStrategyConfig

滾動策略配置項

ScrollStrategyOptions

相關文章