how do I fire onload events for elements within component html in angular2 how do I fire onload events for elements within component html in angular2 typescript typescript

how do I fire onload events for elements within component html in angular2


For loading events, check out this article starting at rookie Mistake #2.

For general events, I found EventEmitter to be useful as a way for child components (custom markup tags) to tell the parent component about the child's events. In the child, create a custom event (a class variable decorated with @Output() ) which will .emit() whenever you determine, and can include parameters of your EventEmitter's specified <data type>. Then the parent can handle the custom event and access the parameters that you bundled within $event. I am using the Angular 2 quickstart files.

Child Script:

import {Component, Output, EventEmitter} from '@angular/core';@Component({  selector: 'my-child',  templateUrl: 'app/my-child.component.html'})export class MyChildComponent {  @Output() childReadyEvent: EventEmitter<string> = new EventEmitter();  ngOnInit(){    //do any lines of code to init the child    console.log("this executes second");    //then finally,    this.childReadyEvent.emit("string from child");          }}

Parent Markup:

<h3>I'm the parent</h3><my-child (childReadyEvent)="parentHandlingFcn($event)"></my-child>

Parent Script:

import {Component} from '@angular/core';import {MyChildComponent} from './my-child.component';@Component({  selector: 'my-parent',  templateUrl: 'app/my-parent.component.html',  directives: [MyChildComponent]})export class MyParentComponent {  ngOnInit(){    console.log("this executes first");  }  parentHandlingFcn(receivedParam: string) {    console.log("this executes third, with " + receivedParam); //string from child  }}

Note: you could also try EventEmitter<MyChildComponent> with .emit(this)


You can grab an instance of your div using Query and then in the ngOnInit trigger the registerDropdown method and pass in the nativeElement from the QueryList<ElementRef>

export class HomeComponent implements OnInit{  public categories: Category[];  public items: Item[];  constructor  (    public element: ElementRef,    private _categoryService: CategoryService,    private _itemService: ItemService,    private _router: Router,    @Query('myDiv') private elList: QueryList<ElementRef>  ){}  public registerDropdown(element:HTMLElement): void  {    console.log(element);  }  ...  public ngOnInit(): any  {    this.getCategories();    this.getItems();    this.registerDropdown(elList.first.nativeElement);  }}


On further reading, it seems that implementing a Spy is the best way to achieve this:

https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#spy