序章

Angular CDK には、ビューポートのサイズとメディアクエリとの一致を検出するサービスを備えたレイアウトパッケージがあります。 これにより、UIを完全に制御し、さまざまな画面サイズに適応できます。

この記事では、AngularプロジェクトにCDKのレイアウトモジュールを適用します。

前提条件

この記事をフォローしたい場合は、次のものが必要になります。

このチュートリアルは、ノードv16.6.1、npm 7.20.3、@angular/core v12.2.0、および@angular/cdkv12.2.0で検証されました。

プロジェクトの設定

@ angle / cli を使用して、新しいAngularプロジェクトを作成できます。

ターミナルウィンドウで、次のコマンドを使用します。

  1. ng new AngularBreakpointsExample --style=css --routing=false --skip-tests

これにより、スタイルが「CSS」(「Sass」、「Less」、「Stylus」ではなく)に設定され、ルーティングがなく、テストがスキップされる新しいAngularプロジェクトが構成されます。

新しく作成されたプロジェクトディレクトリに移動します。

  1. cd AngularBreakpointsExample

次に、@angular/cdkをインストールします。

  1. npm install @angular/cdk@12.2.0

次に、レイアウトモジュールをインポートし、それをNgModuleのインポートリストに追加します。

src / app / app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LayoutModule } from '@angular/cdk/layout';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    LayoutModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

これで、コンポーネントで利用可能なサービスとユーティリティの使用を開始できます。 それぞれについて話し合いましょう。

BreakpointObserver.observeおよびBreakpointStateを使用する

observeメソッドは、タイプBreakpointStateのオブザーバブルを返し、メディアクエリの一致と一致の間にビューポートが変化するかどうかを監視するために使用できます。

ビューポートのサイズが500px未満と500px以上の間で変化した場合に、メッセージがコンソールに記録される例を次に示します。

src / app / app.component.ts
import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  BreakpointState
} from '@angular/cdk/layout';

@Component({ 
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}
  
  ngOnInit() {
    this.breakpointObserver
      .observe(['(min-width: 500px)'])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          console.log('Viewport width is 500px or greater!');
        } else {
          console.log('Viewport width is less than 500px!');
        }
      });
  }
}

注:エラーを防ぐために、app.component.htmlから{{ title }}を削除する必要がある場合もあります。

BreakpointStateインターフェイスは、matchesと呼ばれるブールプロパティを提供します。

Breakpointsを使用する

手書きのメディアクエリを使用する代わりに、Breakpointsオブジェクトを使用することもできます。これにより、一般的なブレークポイントのキーが提供されます。

src / app / app.component.ts
import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  Breakpoints,
  BreakpointState
} from '@angular/cdk/layout';

@Component({ 
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    this.breakpointObserver
      .observe([Breakpoints.Small, Breakpoints.HandsetPortrait])
      .subscribe((state: BreakpointState) => {
        if (state.matches) {
          console.log(
            'Matches small viewport or handset in portrait mode'
          );
        }
      });
  }
}

この例では、Breakpoints.SmallおよびBreakpoints.HandsetPortraitに事前定義されたブレークポイントを使用します。

BreakpointObserver.isMatchedを使用する

1回限りのマッチングでは、代わりにisMatching methodを使用できます。

src / app / app.component.ts
import { Component, OnInit } from '@angular/core';
import {
  BreakpointObserver,
  BreakpointState
} from '@angular/cdk/layout';

@Component({ 
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  constructor(public breakpointObserver: BreakpointObserver) {}

  ngOnInit() {
    if (this.breakpointObserver.isMatched('(min-height: 40rem)')) {
      console.log('Viewport has a minimum height of 40rem!');
    }
  }
}

コンポーネントの初期化時にビューポートの高さが40rem以上の場合、これはメッセージをログに記録します。

MediaMatcherを使用する

MediaMatcherは、JavaScriptのmatchMediaをラップアラウンドするサービスです。 BreakpointObserver.observeと同様に、特定のメディアクエリに対するビューポートサイズの変化を監視するためにも使用できます。

min-widthの幅が500pxかどうかを確認する例を次に示します。

src / app / app.component.html
import { Component, OnInit, OnDestroy } from '@angular/core';
import { MediaMatcher } from '@angular/cdk/layout';

@Component({ 
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  matcher!: MediaQueryList;

  constructor(public mediaMatcher: MediaMatcher) {}

  ngOnInit() {
    this.matcher = this.mediaMatcher.matchMedia('(min-width: 500px)');

    this.matcher.addEventListener('change', this.myListener);
  }

  ngOnDestroy() {
    this.matcher.removeEventListener('change', this.myListener);
  }

  myListener(event: { matches: any; }) {
    console.log(event.matches ? 'match' : 'no match');
  }
}

BreakpointObserver.observeとの違いは、MediaMatcherを使用すると、ネイティブの MatchQueryListオブジェクトにアクセスできることです。これは、特定のシナリオで必要になる場合があります。

注:以前は、この例ではaddListenerremoveListenerを使用していました。 addListener は非推奨であり、addEventListenerは最新のブラウザーに推奨されます。 また、 removeListener は非推奨であり、最新のブラウザーにはremoveEventListenerが推奨されます。

これで、AngularのさまざまなビューポートサイズにUIを反応または適応させるために必要なすべてが揃いました。

結論

この記事では、AngularプロジェクトにCDKのレイアウトモジュールを適用しました。

CDKのレイアウトモジュールAPIリファレンスのドキュメントで学習を続けてください。