Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Expose an Angular Component’s State to the Parent Component

    5 - 6

    Create a simple presentational component in Angular that encapsulates static view and logic decisions, but allows the parent component to set state with Inputs and listen to state changes with Outputs.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: Here we have toggle UI component. It is completely reusable. We could copy and paste it. We can put it anywhere on the page that we want. However, it's not very useful.

    The problem is that all of the decisions have been made for us inside of this toggle component, and the parent component has no way of accessing anything going on inside of this toggle component. What we'd really like is to have some sort of message comeback when the toggle is toggled.

    Now we don't have a show-message function on our app component, so let's add one. We will take the value that comes in and we'll just display it to the console.

    Now if we go back to app component HTML, the red squiggles are gone, but the console is not logging anything on. That's because we haven't set up this output in the toggle component. Let's go to the toggle component. We'll add an output, output of toggled. This is a type EventEmitter and it's going to emit a Boolean value.

    We'll initialize it to a new EventEmitter. Then every time this toggle component is clicked, we will call this doc toggle.emit with the value of the on-state. Now if we go back to the app component here, and we toggle, now you can see there are values being emitted and being displayed in the console.

    Receiving values from the component is great but sometimes you also want to actually set an initial value. Let's see if we can make this work.

    Set the initial on value to true. Now this is throwing an error here because we don't have an on-input on this toggle component, so let's set that up.

    We already have an on property on the toggle component. We just need to decorate it with the add-input decorator. Now if I refresh here, you'll notice that the toggle is set to the on-state initially. Just like before, if I toggle it, you'll see the value emitted to the console.

    We've gone from a toggle component that is totally encapsulated, unable to communicate with the parent component to one that is exposing its state through inputs and outputs that the parent component can control and react to.