1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Getting a reference to a component in the template

Discussão em 'Angular' iniciado por Arnaud Boeglin, Outubro 7, 2024.

  1. I would like to get a reference from a component defined in the template. Let's consider I have the following component:

    @Component({
    selector: 'a-component'
    })
    @View({
    template: '<another-component #anotherComponent></another-component>',
    directives: [AnotherComponent]
    })
    class AComponent {

    callAnotherComponent() {
    anotherComponent.doSomething();
    }

    }


    Obviously, this doesn't work, anotherComponent in my class is not defined. But is there any easy way to do this? In my case, AnotherComponent is supposed to be a popup component and I would like to simply call something like myPopupCmp.showMessage("message").

    I could, of course, use data binding and use it like this in my template: <another-component [text]="popupText" [visible]="isPopupVisible"></another-component>, and use these two members to show it by first setting up the text, and then making it visible. In most cases data binding makes sense, but here I would like to encapsulate the attributes and avoid having to take care of the behavior of the popup from where it's being used.

    edit:

    @EricMartinez I have updated your plnkr after some research, here is a link to the fork : plnkr. The trick is to use @ViewQuery which is used to query directives and dom elements in the View of the Component. I found this in this issue : angular2 github.

    Now the problem is that _results seem to come empty, even though I can see my component if I expand the view in the console, and I can even see its properties, so the data is there somehow but I can't access it. Is there a special way of using QueryLists? Using _results doesn't seem very clean as the _ indicates that it should be private or internal. I also tried to use first but it always brings a null reference.

    Continue reading...

Compartilhe esta Página