Tailwind CSS を使用して Angular で単位コンバーター アプリを構築する

WBOY
リリース: 2024-09-04 16:38:36
オリジナル
668 人が閲覧しました

Building a Unit Converter App in Angular with Tailwind CSS

単位コンバータは、異なる単位間で測定値を変換するための便利なツールであり、さまざまな測定系での作業が容易になります。このチュートリアルでは、ユーザーがメートル、キロメートル、センチメートル、ミリメートルなどのさまざまな長さの単位間で値を変換できるようにする単位変換アプリを Angular で構築します。変換ロジックを実装し、スタイル設定に Tailwind CSS を使用して、視覚的に魅力的でユーザーフレンドリーなインターフェイスを作成します。

目次

  • はじめに
  • プロジェクトのセットアップ
  • 変換ロジックの実装
  • Tailwind CSS を使用したスタイリング
  • アプリケーションの実行
  • 結論
  • コードの探索

はじめに

単位変換アプリは、異なる単位間で測定値を変換するための便利なツールを提供し、さまざまな測定系での作業が容易になります。このプロジェクトでは、ユーザーがメートル、キロメートル、センチメートル、ミリメートルの間で値を変換できるようにする長さの単位に焦点を当てます。このアプリは、ユーザーが値を入力し、変換元および変換先の単位を選択し、変換結果を即座に表示できるシンプルで直感的なインターフェイスを備えています。

プロジェクトのセットアップ

まず、新しい Angular プロジェクトを作成します。 Angular CLI をまだセットアップしていない場合は、次のコマンドを使用してインストールします。

npm install -g @angular/cli
ログイン後にコピー

次に、新しい Angular プロジェクトを作成します。

ng new unit-converter-app
cd unit-converter-app
ログイン後にコピー

プロジェクトが設定されたら、Tailwind CSS をインストールします。

npm install -D tailwindcss
npx tailwindcss init
ログイン後にコピー

tailwind.config.js ファイルを更新して、Tailwind CSS を構成します:

module.exports = {
  content: ["./src/**/*.{html,ts}"],
  theme: {
    extend: {},
  },
  plugins: [],
}
ログイン後にコピー

Tailwind のベース、コンポーネント、ユーティリティを src/styles.css に含めます:

@tailwind base;
@tailwind components;
@tailwind utilities;
ログイン後にコピー

変換ロジックの実装

app.component.ts で、ユニット間の変換ロジックを定義します。

import { Component, inject, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { Meta } from '@angular/platform-browser';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, FormsModule],
  templateUrl: './app.component.html',
  styleUrl: './app.component.scss',
})
export class AppComponent {
  units = signal(['Meter', 'Kilometer', 'Centimeter', 'Millimeter']);
  inputValue = signal(0);
  fromUnit = signal('Meter');
  toUnit = signal('Meter');
  result = signal<number | null>(null);
  errorMessage = signal<string | null>(null);

  meta = inject(Meta);

  constructor() {
    this.meta.addTag({
      name: 'viewport',
      content: 'width=device-width, initial-scale=1',
    });
    this.meta.addTag({
      rel: 'icon',
      type: 'image/x-icon',
      href: 'favicon.ico',
    });
    this.meta.addTag({
      rel: 'canonical',
      href: 'https://unit-converter-app-manthanank.vercel.app/',
    });
    this.meta.addTag({ property: 'og:title', content: 'Unit Converter App' });
    this.meta.addTag({ name: 'author', content: 'Manthan Ankolekar' });
    this.meta.addTag({ name: 'keywords', content: 'angular' });
    this.meta.addTag({ name: 'robots', content: 'index, follow' });
    this.meta.addTag({
      property: 'og:description',
      content:
        'A simple unit converter app built using Angular that converts units like meter, kilometer, and more.',
    });
    this.meta.addTag({
      property: 'og:image',
      content: 'https://unit-converter-app-manthanank.vercel.app/image.jpg',
    });
    this.meta.addTag({
      property: 'og:url',
      content: 'https://unit-converter-app-manthanank.vercel.app/',
    });
  }

  convert() {
    if (!this.validateInput()) {
      return;
    }

    const conversionRates: { [key: string]: number } = {
      Meter: 1,
      Kilometer: 0.001,
      Centimeter: 100,
      Millimeter: 1000,
    };

    const fromRate = conversionRates[this.fromUnit()];
    const toRate = conversionRates[this.toUnit()];

    this.result.set((this.inputValue() * fromRate) / toRate);
  }

  reset() {
    this.inputValue.set(0);
    this.fromUnit.set('Meter');
    this.toUnit.set('Meter');
    this.result.set(null);
    this.errorMessage.set(null);
  }

  swapUnits() {
    const temp = this.fromUnit();
    this.fromUnit.set(this.toUnit());
    this.toUnit.set(temp);
  }

  validateInput(): boolean {
    if (this.inputValue() < 0) {
      this.errorMessage.set('Input value cannot be negative.');
      return false;
    }
    this.errorMessage.set(null);
    return true;
  }
}
ログイン後にコピー

このコードは、長さの単位を変換するためのユーザー入力を処理する、基本的な変換ロジックを設定します。

Tailwind CSS を使用したスタイリング

次に、app.component.html で Tailwind CSS を使用してインターフェイスを設計しましょう:

<div class="min-h-screen flex items-center justify-center bg-gray-100">
  <div class="p-6 max-w-3xl mx-auto bg-white rounded-xl shadow-md space-y-4">
    <h2 class="text-2xl font-bold text-center">Unit Converter</h2>

    <div class="space-y-2">
      <label for="inputValue" class="block text-sm font-medium text-gray-700">Input Value:</label>
      <input type="number" id="inputValue" [(ngModel)]="inputValue"
        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
    </div>

    <div class="space-y-2">
      <label for="fromUnit" class="block text-sm font-medium text-gray-700">From:</label>
      <select id="fromUnit" [(ngModel)]="fromUnit"
        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
        @for (unit of units(); track $index) {
        <option [value]="unit">{{ unit }}</option>
        }
      </select>
    </div>

    <div class="space-y-2">
      <label for="toUnit" class="block text-sm font-medium text-gray-700">To:</label>
      <select id="toUnit" [(ngModel)]="toUnit"
        class="mt-1 block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
        @for (unit of units(); track $index) {
        @if (unit !== fromUnit()) {
        <option [value]="unit">{{ unit }}</option>
        }
        }
      </select>
    </div>

    <div class="flex space-x-2">
      <button (click)="convert()"
        class="w-full bg-indigo-600 text-white py-2 px-4 rounded-md shadow-sm hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Convert</button>
      <button (click)="reset()"
        class="w-full bg-gray-600 text-white py-2 px-4 rounded-md shadow-sm hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">Reset</button>
      <button (click)="swapUnits()"
        class="w-full bg-yellow-600 text-white py-2 px-4 rounded-md shadow-sm hover:bg-yellow-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-yellow-500">Swap</button>
    </div>

    @if (errorMessage()){
    <div class="text-red-500 text-center mt-4">{{ errorMessage() }}</div>
    }

    @if (result() !== null) {
    <h3 class="text-xl font-semibold text-center mt-4">Result: {{result()}}</h3>
    }
  </div>
</div>
ログイン後にコピー

このデザインでは、Tailwind CSS クラスを使用して、さまざまなデバイス間でシームレスに調整できるシンプルで応答性の高い UI を作成します。

アプリケーションの実行

次のコマンドを使用してアプリケーションを実行します。

ng serve
ログイン後にコピー

http://localhost:4200/ に移動して、単位コンバータ アプリの動作を確認します。値を入力し、ドロップダウン メニューから単位を選択し、[変換] をクリックすると、結果が即座に表示されます。

結論

おめでとうございます!スタイル設定に Tailwind CSS を使用して、Angular で単位コンバータ アプリを正常に構築しました。このプロジェクトでは、長さの単位を変換するための貴重なツールを提供する、機能的で視覚的に魅力的な Web アプリケーションを作成する方法を示します。ユニットオプションを追加したり、デザインを改善したり、追加機能を実装したりすることで、アプリをさらに強化できます。

コーディングを楽しんでください!


必要に応じてコンテンツを自由にカスタマイズしてください。ご質問がある場合、またはさらにサポートが必要な場合はお知らせください。あなたのプロジェクトの幸運を祈ります! ?

コードを調べる

コードを詳しく調べるには、GitHub リポジトリにアクセスしてください。


以上がTailwind CSS を使用して Angular で単位コンバーター アプリを構築するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!