Sending some event info from a child component to the parent component

Issue

I want to pass a int value from a child component to its parent component. The event itself arrives properly but I do fail on adding an Event parameter in the receiving method of the parent.

UPDATE: edited code to shrunk down, but complete example


import 'package:angular2/core.dart';

class MyItem {
  int id = 1;
}



@Component(
    selector: 'my-list',
    directives: const [MyListItem],
    template: '''
<div *ngFor='let myItem of myItems'>
  <my-list-item [myItem]='myItem' (dirtiesParent)='doInit($event)'></my-list-item>
</div>
''')
class MyList {

  @Input()
  List<MyItem> myItems = [ new MyItem() ];

  void doInit() {
    print("got event");
  }

}



@Component(
    selector: 'my-list-item',
    template: '''
<div>id {{myItem.id}}<button (click)='doDelete()'>delete</button></div>
''')
class MyListItem {

  @Input()
  MyItem myItem;
  @Output()
  EventEmitter<int> dirtiesParent = new EventEmitter();

  void doDelete() {
    dirtiesParent.add(myItem.id);
  }

}

Solution

I think you just improperly escaped the $. Try this:

class MyItem {
  int id = 1;
}

@Component(
    selector: 'my-list',
    directives: const [MyListItem],
    template: '''
<div *ngFor='let myItem of myItems'>
  <my-list-item [myItem]='myItem' (dirtiesParent)='doInit(\$event)'></my-list-item>
</div>
''')
class MyList {
  @Input()
  List<MyItem> myItems = [new MyItem()];

  void doInit(int id) {
    print("got event for id $id");
  }
}

@Component(
    selector: 'my-list-item',
    template: '''
<div>id {{myItem.id}}<button (click)='doDelete()'>delete</button></div>
''')
class MyListItem {
  @Input()
  MyItem myItem;
  @Output()
  EventEmitter<int> dirtiesParent = new EventEmitter();

  void doDelete() {
    dirtiesParent.add(myItem.id);
  }
}

This works for me (it prints “got event for id 1”). Note that I also added the expected parameter to doInit().

Answered By – filiph

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.