首頁 > web前端 > js教程 > 主體

使用 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: [],
}
登入後複製

在 src/styles.css 中包含 Tailwind 的基礎、元件和實用程式:

@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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!