Angular - 5.11-Use of local references in templates
Back in the application we built during the first lessons of this course, we used our anti element componentcockpit server using output and input to pass data around our own custom property and event link.
Now in the cockpit, I’m currently using a bidirectional data link to get the server name and contents. There’s nothing wrong with that, but we may not need to use a two-way data link.
Since I only want to save or use the data when I click on the button to add the add server or add server blueprint, all that is needed is to retrieve the value of the entry at that time, and there is a nice way to do that. So I’m going to duplicate that and comment on the old solution, and now I’m going to structure it on a few lines and remove the two-way link.
A local reference can be placed on any HTML element, so not just on an input element, on everything you see here in the template, and you add with a hashtag and a name of your choice, such as server name.
Since this is, well, what is this reference going to contain? A reference to this element. So maybe server name input. The reference, as I just said, will have a reference to that. So no value, we entered there in the whole HTML element with all its properties.
We can see this, if we pass it now as an argument once we click on the server on Add Server. Here I can pass server name input because the other important thing you need to know about references, in addition to how to create them, is that you can use them everywhere in your template, but only there, not inside your TypeScript code, only in the model. But we call the method here inside the model, of course.
Here we can use the server name entry, and this is how we can pass it to the TypeScript code. Because in "add a server", we now know that we will receive the input name. You could also call it "nameInput".
And if we record this, we can analyze what it really means, what we actually got here. So let’s save this and let our application reload.
Now, if I test something and put something in here, and when I click on "add server", of course, it doesn’t work here because we’re not getting the data correctly right now. You can see that we actually got the input itself. So here’s the element we got here, this is what the local reference gives us, the element with all its properties.
Local references are a handy feature to access certain elements in your template and use them either directly in the template or pass them as argument to methods to use them in TypeScript code. Now that we have this local reference, we can get rid of the bidirectional data link that we used before to get the server name and content.