Thai Tran
Thai Tran

Reputation: 9935

Angular 2 - How to access directives from Component

I attached a dialog component as a directives in order to show it on the main component page when I click on the button on the main page (which link to the main component). This is how I did it

In the template

<button id="goToTasksCases" class="btn btn-success btn-lg" (click)="doShowStartNewCase($event)">START A NEW CASE</button>
<modal-new-case></modal-new-case>

In the component

@Component({
    selector: 'case-index'
})
@View({
    templateUrl: 'client/app/case/case.index.html',
    directives : [ModalNewCaseComponent]
})
export class CaseIndexComponent {
    doShowStartNewCase(event: any) {
        // how can I access the ModalNewCaseComponent
    }    
}

However, i need to set some values for the child component (ModalNewCaseComponent) after some callback from Rest service. How can I achieve that with the current setup ?

Upvotes: 6

Views: 2765

Answers (1)

Minko Gechev
Minko Gechev

Reputation: 25682

You can query the view children by:

@Component({
    selector: 'case-index',
    templateUrl: 'client/app/case/case.index.html',
    directives : [ModalNewCaseComponent]
})
export class CaseIndexComponent {
    @ViewChild(ModalNewCaseComponent)
    modal: ModalNewCaseComponent;

    afterViewInit() {
        // this.modal will have value
    }

    doShowStartNewCase(event: any) {
        // how can I access the ModalNewCaseComponent
    }    
}

You can find more about ViewChildren and ContentChildren here.

Upvotes: 14

Related Questions