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.
Instructor: [00:00] 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.
[00:16] 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.
[00:40] 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.
[00:57] 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.
[01:32] 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.
[02:02] 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.
[02:14] 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.
[02:23] 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.
[02:51] 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.
Yep, it looks like they’re missing this line angular.json:
"styles": ["src/styles.css"],
Yep, it looks like they’re missing this line angular.json: "styles": ["src/styles.css"],
That seemed to do the trick. Thanks!
I ran the code on https://github.com/eggheadio-projects/advanced-angular-component-patterns but fail to get the look of a slider on the toggle vide, as in the video. Is there something missing with the code?