Total Pageviews

2017/03/10

[Agnular2] Notifying parent Components that something has happened via events

Scenario

If we would like to tell the parent Component that the child component has added or deleted subtask. How to implement in Angualr2 ?


How-to
To create a custom event, we can use the new @Output decorator. So let's start by creating a new instance of an Event Emitter and decorate the property with the @Output decorator.

Then we've got an event emitter in place, let's call its emit method, callParent(), to raise the event and pass to parent component. 

The child component's code snippet looks like:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
@Component({
  selector: 'sub-task',
  directives: [MODAL_DIRECTIVES, SELECT_DIRECTIVES, NgClass],
  providers: [SubtaskService, UserService, IssueService, ProjectService],
  templateUrl: 'sub.task.html'
})
export class SubTaskComponent implements OnInit {

  @Input() issue: Issue;
  @Input() watchers: Watcher[];

  @Output() refreshIssueEvent = new EventEmitter();
  
  callParent() {
    this.refreshIssueEvent.emit(this.issue.id);
  }
  
  //...
}  


The parent component receives that event and its payload. We use event binding to bind to this notify event and call a method.

Our final step is to provide the refreshIssue method to execute when the notify event occurs. 
1
2
3
<div class="container" *ngIf="issue.id">
  <sub-task [issue]="issue" [watchers]="issue.watchers" (refreshIssueEvent)="refreshIssue($event)"></sub-task>
</div>

We have to pass the $event to parent component's handler because that variable holds the event payload.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
@Component({
  selector: 'issue-detail',
  templateUrl: 'issue.detail.html',
  providers: [IssueService]
})
export class IssueDetailComponent implements OnInit, OnDestroy {
  refreshIssue(issueId: number){
    this.issueService.getIssue(issueId.toString()).subscribe(
      data => {
        this.issue = data;
      }
    );
  }
  //...
}

No comments: