2016-03-22 3 views
8

मैं इस तरह एक निर्देश है -कोणीय 2 - यह कैसे में निर्देश के लिए उपयोग और एक सदस्य समारोह कॉल करने के लिए

@Directive({ 
    selector: 'someDirective' 
}) 
export class SomeDirective{   
    constructor() {}  
    render = function() {} 
} 

और फिर मैंने निर्देश

import {SomeDirective} from '../../someDirective'; 
@Page({ 
    templateUrl: '....tem.html', 
    directives: [SomeDirective] 
}) 
export class SomeComponent { 
     constructor(){} 
     ngAfterViewInit(){//want to call the render function in the directive 
} 

का आयात कर रहा हूँ ngAfterViewInit में, मैं चाहता हूँ निर्देश में रेंडर समारोह को कॉल करने के लिए। यह कैसे करें?

उत्तर

12

यह पुराना तरीका है,

@Directive({ 
    selector: 'someDirective' 
}) 
export class SomeDirective{   
    constructor() {}  
    render() { 
     console.log('hi from directive'); 
    } 
} 

import {Component,ViewChild} from 'angular2/core'; 
import {SomeDirective} from '../../someDirective'; 
@Component({ 
    templateUrl: '....tem.html', 
    directives: [SomeDirective] 
}) 
export class SomeComponent { 
     @ViewChild(SomeDirective) vc:SomeDirective; 
     constructor(){} 
     ngAfterViewInit(){ 
      this.vc.render(); 
     } 
} 

Angular2 के नए संस्करण के लिए

, पालन जवाब यहाँ दी

Calling function in directive

+0

उत्तर के लिए धन्यवाद, मैं इस कोशिश की है के रूप में आप से कहा, लेकिन मुझे त्रुटि मिल रही है - वाक्यविन्यास त्रुटि - @ViewChild (कुछ निर्देशक) vc: कुछ निर्देशक; लाइन के कोलन ':' पर। मैं आयनिक 2 का उपयोग कर रहा हूं। मैंने दोनों तरीकों को आयात करने की कोशिश की ---> 'कोणीय 2/कोर' से आयात {ViewChild}; और 'आयनिक-कोणीय' से {ViewChild} आयात करें; –

+0

ओह! मैं आयनिक framwork नहीं है। इसलिए उस मामले में आपकी मदद नहीं कर सकता है। लेकिन मुझे यकीन है कि इस तरह ViewChild का उपयोग किया जाता है। – micronyks

+0

अरे आप बिल्कुल सही हैं, सिवाय इसके कि मैं ES6 में कोड लिख रहा हूं। तो, टीएस में कोड लिखा और इसे पार किया और चीजें काम किया। यह अच्छा होगा अगर आप मुझे बता सकें कि ES6/ES5 में इसे कैसे लिखना है। धन्यवाद। –

संबंधित मुद्दे