Header Ads Widget

LWC with TypeScript: Todo App Example

LWC introduction:

Lightning Web Components (LWC) is a modern, standards-based framework for building web components on the Salesforce platform. It is a part of the Lightning Component framework and is designed to provide a lightweight, high-performing, and developer-friendly approach to building user interfaces for Salesforce applications.
LWC leverages web standards such as HTML, CSS, and JavaScript to create reusable and encapsulated components that can be easily composed to build complex user interfaces. It follows a component-based architecture, where each component represents a self-contained and reusable unit of functionality.

LWC provides a templating syntax. This ensures that the HTML template remains a declarative representation of the component's structure (just the view), while the JavaScript logic resides in the component class file. All the logics are written within the component's JavaScript file.
This helps maintain the separation of concerns between the template and the JavaScript logic and ensures adherence to LWC's architectural principles.

Here's an example of a Todo app built using Lightning Web Components (LWC) and TypeScript:

  1. Create a new TypeScript based LWC App:
    • In a comandLine (terminal), run this command npm init lwr@latest. It will initiate a LWC based project
    • For Project directory name, enter Todo_Example_App. You can choose other name too.
    • Accept the generated package name by pressing the Enter key.
    • For Select the type of project, accept the default, Single Page App.
    • For Select a project template: select LWC (TypeScript)
    • For Select a variant, accept the default, Markdown Static Site.
        cd Todo_Example_App
        npm install
        npm run dev
        

    your application will run on PORT 3000. http://localhost:3000

    Now, you can go to src/modules/example/app directory. Here you will se app.html, app.js and app.css. You can start editing these files and see the changes on http://localhost:3000

  2. Replace app.ts file code with below code
    import { LightningElement, track } from 'lwc';
    
    interface Todo {
      id: number;
      text: string;
      completed: boolean;
      completedClass: string;
    }
    
    export default class TodoApp extends LightningElement {
      @track todoList: Todo[] = [];
      @track newTodo = '';
    
      handleInputChange(event: Event) {
        const inputElement = event.target as HTMLInputElement;
        this.newTodo = inputElement.value;
      }
    
      handleAddTodo() {
        if (this.newTodo) {
          this.todoList.push({ id: Date.now(), text: this.newTodo, completed: false, completedClass: '' });
          this.newTodo = '';
        }
      }
    
      handleDelete(event: Event) {
        const todoId = event.target?.dataset?.id;
        if (todoId) {
          this.todoList = this.todoList.filter(todo => todo.id !== Number(todoId));
        }
      }
    
      handleComplete(event: Event) {
        const todoId = event.target?.dataset?.id;
        const completed = (event.target as HTMLInputElement).checked;
    
        if (todoId) {
          this.todoList = this.todoList.map(todo => {
            if (todo.id === Number(todoId)) {
              return { ...todo, completed, completedClass: completed ? 'completed' : '' };
            }
            return todo;
          });
        }
      }
    }
    
  3. Replace app.html code with below cdoe
    <template>
      <div class="container">
        <h1>Todo App</h1>
        <div class="input-container">
          <input type="text" value={newTodo} oninput={handleInputChange} />
          <button onclick={handleAddTodo}>Add</button>
        </div>
        <ul class="todo-list">
          <template for:each={todoList} for:item="todo" for:index="index">
            <li key={todo.id}>
              <input type="checkbox" data-id={todo.id} onchange={handleComplete} />
              <span class={todo.completedClass}>{todo.text}</span>
              <button data-id={todo.id} onclick={handleDelete}>Delete</button>
            </li>
          </template>
        </ul>
      </div>
    </template>
  4. Style the component: Replace the app.css file code with below code
    .container {
        max-width: 400px;
        margin: 0 auto;
        padding: 20px;
        background-color: #f5f5f5;
        border-radius: 8px;
      }
      
      h1 {
        text-align: center;
        color: #333;
      }
      
      .input-container {
        display: flex;
        margin-bottom: 20px;
      }
      
      input[type="text"] {
        flex-grow: 1;
        padding: 8px;
        border: 1px solid #ccc;
        border-radius: 4px;
      }
      
      button {
        padding: 8px 16px;
        background-color: #0070e0;
        color: #fff;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      
      .todo-list {
        list-style-type: none;
        padding: 0;
      }
      
      li {
        display: flex;
        align-items: center;
        margin-bottom: 10px;
      }
      
      input[type="checkbox"] {
        margin-right: 10px;
      }
      
      .completed {
        text-decoration: line-through;
        color: gray;
      }
      
      button[data-id] {
        margin-left: 10px;
      }
        
  5. Now you can run the app, you will see the Todo App like below

Happy Coding.... 🙂

Post a Comment

0 Comments