Home > Mobile >  How can I press enter on keyboard to save my todo
How can I press enter on keyboard to save my todo

Time:06-18

I'm wanting to be able to press enter to add my todo, so far clicking button adds it

 <h1 style="text-align:center">Todo List</h1>
    
    <div >
      <div >
        <div >
          <div >
            <input type="text"  placeholder="Enter Todo" aria-label="Enter Todo" aria-describedby="button-addon2" [(ngModel)]="newTodo">
            <button  type="button" id="button-addon2" style="color: white" (click)="saveTodo() ">Add Todo</button>
        
          </div>
          <table >
            <tbody>
              <tr *ngFor="let todo of todos; let i = index">
                <th scope="row">{{i 1}}</th>
                
                <td  (click)="done(i)">{{todo.name}}</td>
                <td style="color: red;font-weight: bold;"(click)="remove(i)" >X</td>
              </tr>  
          </table>
        </div>
      </div>
    </div>

CodePudding user response:

You can do this by 2 ways. First way is to use form to enter todo and make save button as type="submit" then your todo will be saved as soon as you press enter. Second way is to use some javascript. like this:-

var input = document.querySelector("input[type='text']");

// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
  // If the user presses the "Enter" key on the keyboard
  if (event.key === "Enter") {
    // Cancel the default action, if needed
    event.preventDefault();
    // Trigger the button element with a click
    document.getElementById("button-addon2").click();
  }
});

CodePudding user response:

Try event binding

<input type="text" (keyup.enter)="saveTodo()" [(ngModel)]="newTodo">

Read more about it here: https://angular.io/guide/event-binding

  • Related