Home > Back-end >  Angular: Event Emitter
Angular: Event Emitter

Time:03-11

I have an "add/close" toggle button on my main task component and another separate add-task component to control my adding of new tasks. I have created an event emitter from my add-task component to my main task component for the main task component to receive the adding of new tasks. How do I also control the "add/close" toggle to automatically close my add-task component once the submit button is pressed?

This is my main task component (task.component.html)

<div >
    <div >
        <h1>Tasks</h1>
        <div >
            <button
                
                (click)="toggleAddButton()"
                *ngIf="showAddTasks"
            >
                Close
            </button>
            <button
                
                (click)="toggleAddButton()"
                *ngIf="!showAddTasks"
            >
                Add
            </button>
        </div>
        <app-add-task (onAddTask)="addTask($event)"></app-add-task>
        <table >
        </table>
    </div>
</div>

This is my main task component (task.component.ts)

import { Component, OnInit } from '@angular/core';
import { TaskService } from '../../services/task.service';
import { Task } from '../../Task';
import {AddTaskUiService} from '../shared/services/add-bid-ui.service';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-tasks',
  templateUrl: './tasks.component.html',
  styleUrls: ['./tasks.component.css'],
})
export class TasksComponent implements OnInit {
  tasks: Task[] = [];

constructor(
    private taskService: TaskService,
    private addTaskUiService: AddTaskUiService
   ){ 
     this.subscription = this.addTaskUiService
      .onToggle()
      .subscribe((value) => (this.showAddTasks = value));
   }

  showAddTasks: boolean = false;
  subscription: Subscription = new Subscription;

  ngOnInit(): void {
    this.taskService.getTasks().subscribe((tasks) => (this.tasks = tasks));
  }

  deleteTask(task: Task) {
    this.taskService
      .deleteTask(task)
      .subscribe(
        () => (this.tasks = this.tasks.filter((t) => t.id !== task.id))
      );
  }

  toggleReminder(task: Task) {
    task.reminder = !task.reminder;
    this.taskService.updateTaskReminder(task).subscribe();
  }

  addTask(task: Task) {
    this.taskService.addTask(task).subscribe((task) => this.tasks.push(task));
  }
}


This is my add task component (add-task.component.html)

<form *ngIf="showAddTask"  (ngSubmit)="onSubmit()">
  <div >
    <label for="text">Task</label>
    <input
      type="text"
      name="text"
      [(ngModel)]="text"
      id="text"
      placeholder="Add Task"
    />
  </div>
  <div >
    <label for="day">Day & Time</label>
    <input
      type="text"
      name="day"
      [(ngModel)]="day"
      id="day"
      placeholder="Add Day & Time"
    />
  </div>
  <div >
    <label for="reminder">Set Reminder</label>
    <input
      type="checkbox"
      name="reminder"
      [(ngModel)]="reminder"
      id="reminder"
    />
  </div>
  <input type="submit" value="Save Task"  />
</form>

This is my add task component (add-task.component.ts)

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { UiService } from '../../services/ui.service';
import { Subscription } from 'rxjs';
import { Task } from '../../Task';

@Component({
  selector: 'app-add-task',
  templateUrl: './add-task.component.html',
  styleUrls: ['./add-task.component.css'],
})
export class AddTaskComponent implements OnInit {
  @Output() onAddTask: EventEmitter<Task> = new EventEmitter();
  text: string;
  day: string;
  reminder: boolean = false;
  showAddTask: boolean;
  subscription: Subscription;

  constructor(private uiService: UiService) {
    this.subscription = this.uiService
      .onToggle()
      .subscribe((value) => (this.showAddTask = value));
  }

  ngOnInit(): void {}
  
   ngOnDestroy() {
        // Unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }

  onSubmit() {
    if (!this.text) {
      alert('Please add a task!');
      return;
    }

    const newTask: Task = {
      text: this.text,
      day: this.day,
      reminder: this.reminder,
    };

    this.onAddTask.emit(newTask);

    this.text = '';
    this.day = '';
    this.reminder = false;
  }
}

CodePudding user response:

Perhaps after submitting you could turn the off showAddTask? Seeing that you are tying to manage this state through a service, perhaps turning boolean on this.uiService.onToggle() would be better, but that's up to you.

  onSubmit() {
    if (!this.text) {
      alert('Please add a task!');
      return;
    } else {
      this.showAddTask = false;
    }
  • Related