Luther-Varys
1/8/2017 - 1:48 PM

@ViewChild - access a CHILD COMPONENT from a parent. This is useful when you want to fire a function in a child component.

@ViewChild - access a CHILD COMPONENT from a parent. This is useful when you want to fire a function in a child component.

//We can all use the # ref symbol to ref. any element
//And use Jquery to refrence it as well

//HTML TEMPLATE
<div #refsummernote >Hello Summernote</div>


//COMPONENT
//USE property .nativeElement
@ViewChild('refsummernote') refsummernote: ElementRef;
let $mysummernote = ($(this.refsummernote.nativeElement) as any);  //<--nativeElement

//Print innerHtml, result: "Hello Summernote"
console.log("refsummernote: "+ $(this.refsummernote.nativeElement).html()); 
//We can also do the same thing with a local variable. 
//Instead of trying to load the particular class, we can do: 
//template variable #reference to the child element

import { Component, ViewChild } from '@angular/core';
import { UserProfile } from '../user-profile';

@Component({
  template: '<user-profile #myProfile (click)="update()"></user-profile>'
})
export class MasterPage {
  @ViewChild('myProfile') userProfile: UserProfile
  constructor() { }
  update(){
    this.userProfile.sendData();
  }
}
//When use the user-profile on our parent component, 
//we can reference the UserProfile component class and 
//then assign it to a local property:

import { Component, ViewChild } from '@angular/core';
import { UserProfile } from '../user-profile';

@Component({
  template: '<user-profile (click)="update()"></user-profile>',
})
export class MasterPage {
  // ViewChild takes a class type or a reference name string.
  // Here we are using the type
  @ViewChild(UserProfile) userProfile: UserProfile

  constructor() { }

  ngAfterViewInit() {
    // After the view is initialized, this.userProfile will be available
    this.update();
  }

  update() {
    this.userProfile.sendData();
  }
}
//http://learnangular2.com/viewChild/
//For example, our <user-profile> component can have a method called sendData()
//that needs to be accessed by a parent component.

@Component({
  selector: 'user-profile'
})

export class UserProfile {
  constructor() {}
  sendData() {
    //send data
  }
}