0

I'm reading a book about angular and I try to write a sample (and simple) code emit an event with an output. Basically, I have a list of TodoModel, displayed in my child component, with a button to delete one TodoModel.

On my child component I have :

import { Component , EventEmitter, Input , Output} from '@angular/core';
import { TodoModel } from '../todo/todo.model';

@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent {
  
  @Input()
  todo : TodoModel = {
    text: "",
    isFini: false
  };

  @Output()
  deleteTrigerred : EventEmitter<TodoModel> = new EventEmitter<TodoModel>();

  deleteTodo()
  {
    alert("todoCompoment deleteToDo. this.todo.text = " + this.todo.text );
    this.deleteTrigerred.emit(this.todo);
  }

}

In the child template file :

<div>
    {{todo.text}} 
    <input type = "checkbox" [(ngModel)] = "todo.isFini" />
    <button (click) = "deleteTodo()">Supprimer</button>
</div>

The parent component display the list. Here is the ts file :

import { Component , Input} from '@angular/core';
import { TodoModel } from '../todo/todo.model';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent {

  titreTest = 'Testgdfg';

  newToDoText : string = "";
  isFini : boolean = false;

  todoList : TodoModel[] = []; 

  addToDo(){

    // console.log("dans addTodo");
    // alert('dd');

    if(this.newToDoText)
    {
      this.todoList.push({text : this.newToDoText , isFini : this.isFini});
      this.newToDoText = "";
    }
    else{
      alert('Aucun text saisie');
    }
  }

  deleteTodo(todo : TodoModel)
  {
    let index = this.todoList.findIndex(t => { return t === todo});
    

    alert("testCompomonent deleteTodo : " + todo.text);

    if(index != -1)
      this.todoList.splice(index , 1);
    else
      alert("pas de todo trouve");
  }


}

And here is the template file :

<h1>{{titreTest}}</h1>

<input type = "text" [(ngModel)] = "newToDoText" placeholder = "Nouveau todo..." />
<input type = "checkbox" [(ngModel)] = "isFini" />

<button (click) = "addToDo()">Ajouter todo</button>

<app-todo *ngFor = "let todo of todoList" [todo] = "todo" (deleteTriggered) = "deleteTodo($event)"></app-todo>

But I got :

Argument of type 'Event' is not assignable to parameter of type 'TodoModel'.

But normally, $event is a TodoModel type.

Thanks

  • 2
    In your view, the event name is `deleteTriggered` (`(deleteTriggered) = "deleteTodo($event)"`). But in your `ToDoComponent` the variable for Output binding is `deleteTrigerred`. Looks like a typo error? – Yong Shun Mar 28 '23 at 13:16

0 Answers0