Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Get component instance

I have two components like these:

@Component({
    selector: 'comp1',
    template: `<h1>{{ custom_text }}</h2>`
})
export class Comp1 {
    custom_text:string;
    constructor(text:string) {
        this.custom_text = text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1></comp1>
    `
})
export class Comp2 {
    constructor() {
        // ...
        // How to send my own text to comp1 from comp2
        // ...
    }
}

Is it possible to send my own text from comp1 to comp2?

Is it possible to get the comp1 instance from comp2?

like image 328
Jon... Avatar asked Oct 22 '25 16:10

Jon...


2 Answers

comp2 is the parent of comp1, so

  • to send data from child to parent (comp1 to comp2) add an OutputProperty to the child:
    @Output() someEvent = newEventEmitter();
    and emit() an event on it: this.someEvent.emit('some text');
    The parent will need to bind to the output property/event: <comp2 (someEvent)="someHandler()"></comp2>
  • to get a reference to an instance of a child component (comp2 gets an reference to comp1), use @ViewChild or @Query in comp2: @ViewChild(Comp1) viewChild:comp1; You can then access this.comp1 in ngAfterViewInit(), or later in the component's lifecycle.
like image 192
Mark Rajcok Avatar answered Oct 25 '25 08:10

Mark Rajcok


Yes it is very easy to accomplish that,

Checkout the Tutorial : MULTIPLE COMPONENTS Part 3 of the Angular2 Tutorials to see how to send inputs.

@Component({
    selector: 'comp1',
    template: `<h1>{{customText}}</h2>`,
    inputs: ['customText']
})
export class Comp1 {
    public customText:string;
    constructor(text:string) {
        this.customText= text;
    }

 // ngOnChange to make sure the component is in sync with inputs changes in parent
 ngOnChanges() {
       this.customText= text;
    }
}

/*********************************************/

@Component({
    selector: 'comp2',
    directives: [Comp1],
    template: `
    <b>Comp 2</b>
    <comp1 customText = "My Custom Test"></comp1>
    `
})
export class Comp2 {
    constructor() {
    }
}

Try it out and let me know how it went.

like image 30
C B Avatar answered Oct 25 '25 08:10

C B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!