Tailwind CSS를 사용하여 Angular에서 단위 변환기 앱 구축

WBOY
풀어 주다: 2024-09-04 16:38:36
원래의
672명이 탐색했습니다.

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.comComponent.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.comComponent.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에서 단위 변환기 앱을 성공적으로 구축했습니다. 이 프로젝트는 길이 단위를 변환하는 데 유용한 도구를 제공하는 기능적이고 시각적으로 매력적인 웹 애플리케이션을 만드는 방법을 보여줍니다. 더 많은 유닛 옵션을 추가하거나, 디자인을 개선하거나, 추가 기능을 구현하여 앱을 더욱 향상시킬 수 있습니다.

즐거운 코딩하세요!


필요에 따라 콘텐츠를 자유롭게 맞춤설정하세요. 궁금한 점이 있거나 추가 지원이 필요하면 알려주시기 바랍니다. 프로젝트에 행운이 있기를 바랍니다! ?

코드 탐색

GitHub 저장소를 방문하여 코드를 자세히 살펴보세요.


위 내용은 Tailwind CSS를 사용하여 Angular에서 단위 변환기 앱 구축의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!