Angular : Creating re-usable components

Joshua Markasky
3 min readJan 14, 2021

Component based architecture, we all know what's the purpose. To create re usable components to cut down code but time and time again I do not see this implemented. So many times I run into a code based with components with thousands of lines of code and forms with just multiple similar input’s. So I’m going to give a real world fast example of how to create re-usable components.

Lets start with a very basic form

So at first you might look at this and be like ‘what’s wrong with this form’. Well we are using the same input 3 times in a row. It doesn’t make sense to work in a component based frame work and do this. so what’s solution? Simple, we are going to create one new component.

Now lets set up our html and typescript

We created very simple html that show a basic input bar. We wired that input up to a a variable called ‘dataToSet’ in the typescript. We also make it @Input() that means we are expecting data from a parent component. We would use this to set the input to a certain value, such as if we are creating a edit form. Then we create a keyup event, every time the user types it send what they are typing up to the parent component. So now lets replace all three of those inputs we had in that form with this one component.

We replace all the inputs with the component, we are passing data between them constantly. We created a component that can be used in any form that needs a input. Of course this is just small scaled. Think of all the re-usable components you could create to help make the code easy to maintain.

Connect with me on linkedIn: www.linkedin.com/in/joshua-markasky47

follow me on Twitter: https://twitter.com/MarkaskyJ

Checkout my YouTube channel: https://www.youtube.com/channel/UCgRkJcniRghYpSpzKQlEYvQ

--

--