How to use @Input and @Output in Angular 17?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello and welcome everyone I am a zafur and today we are diving into the exciting world of angular 17 thank you for joining me on this journey angular 17 the latest version of one of the most popular front-end web development Frameworks brings a host of new features and improvements this framework known for robustness and versatility continues to be Cornerstone in the development of dynamic web application in this tutorial we are going to focus on two powerful features of angular 17 the input and output decorators these are fundamental concepts of angular that allow components to communicate with each other creating a dynamic and interactive user experience whether you are a beginner looking to get your feet wet or an experienced developer aiming to brush up your skills understanding input and output is crucial they are backbone of component interaction in angular applications so why are these decorators so important well in angular applications are built using a hierarchy of components input allows a parent component to pass data to a child component while output enables a child to send data back up to its parent this two-way communication is essential for building responsive data driven interfaces throughout this tutorial we will explore how input and output can be used to solve real world problems enhance user interaction and make your applications more efficient and user friendly we will look at practical examples provide code Snippets and delve into the nuances of these decorators so get ready to level up your angular skills let's get started let's begin with the basics in angular components are the main building blocks of your application but but how do these components talk to each other that's where input and output come in input and output are decorators in angular that allows components to share data think of input as a way for a parent component to send data to child component it's like passing a message down to hierarchy on the other hand output works in the opposite direction it allows a child component to send data back to its parent this is like responding back to the parent component together input and output create a system of communication between components allowing them to be modular yet interconnected now let's set up our angular 17 project I will guide you through the process step by step first we need to install angular CLI which is the command line interface for angular if you haven't installed it yet run this command in your terminal first of all open your terminal and type it npm install DG angular / CLI so this would install it globally in your machine I already have it installed so I will not run it again but I will show you my version that I have currently installed here so you can see I have angular 17 installed with node GS 18.6 and npm 9.5.1 installed already on it with angular CLIA installed let's create a new angular project execute this command NG new and your project name this can be any name whatever you prefer so this command scaffolds a new angular application when prompted select the options suitable for your project like whether to add angular routing or which stylesheet format to use I already have generated my angular project so I will not run it again I will just open it in my editor that would be V Studio code you can use any your any of your favorite editors to start development server you just need to run a command that is NG serve so if you add- O then it will open your browser and open the URL of your angular server in the browser automatically so with that you should see your new angular app running that's it you have successfully set up your angular 17 project next we will dive into the creating components and implementing input and output decoration now that we have our angular environment set up let's dive into input decorator input is a decorator that marks a class field as an input property this means it can receive value from its parent component imagine you have a parent component and you want to pass some data to its child component this is where input comes into play it's like giving your child component a little mailbox where it can receive messages or in our case data from the parent so let's create a child component that will receive the data from its parent so first generate a new component by using angular C so for that type NG generate component space child you can give it whatever name you prefer so with that you can see that the child folder has been created along with its files now let's open the child. component.ts file in your editor and let's define an input property here make sure to import the input from the angular core and now I will give it a name child message and the type would be string okay and we have to either make it optional or we have to initialize it with the default value okay so it's totally up to us so here child message is marked with the input decorator which means it it can accept a value from its parent component now let's bind this property in the parent components template so let's go to our parent component that is app component but in order to use the child component in here if you are using App module if you are not using Standalone component then you will simply declare the child component in that relevant module but if you are using Standalone components like me you can just directly import the child comp component in the Imports array of the app component now you are able to add the selector of that child component like this okay now if you re reload it you will see that the child Works text that is coming from the app child component and now let's add the input child message and give it a value hello from parent okay now let's go back to the child component. HTML and I will replace it with with the input variable that is child message now you will see the message that we passed from the parent is being shown in the child so in this parents template we are using the child component selector app- child and binding the child message property the value hello from the parent will be passed down to the child component so this demonstrates how input allows us to pass data from parent to child making our components more Dynamic and reusable and that's the power of input in angular it's simple yet effective way to communicate between components next up we will explore the output decorator and see how it complement input in facilitating component interaction having understood input let's explore its counterpart the output decorator while input allows a child component to receive data output enables a child component to send data back to its parent output is often often used in conjunction with event emitter which is class in angular that allows you to emit custom events when a child component needs to communicate with its parent it emits an event which the parent can listen to and respond accordingly so let's enhance our child component to emit an event to to the parent we'll start by importing the event emitter and output in our child component so let's go back to our child component.ts file and here make sure to import the event emitter and output so now let's define our output variable here and give it a name message event and initialize the event emitter and give it the type string that would be emitted now let's define a function send message to parent and now I will use this do message message event. Emit and give it a text message from child so here message event is an instance of event emitter marked with output decorator this setup allows the child component to emit messages the send message to parent function it triggers the emission of our message now let's switch to child components template file and here I will add a button and within that I will just add a text send message to parent okay and here I will add the click event on this button that will call a function send message to parent so in the child's template we have a button when clicked it calls the send message to parent method triggering the event now in the parents components template we will listen for this event so let's go back to the app component. HTML and here to in order to listen it we will register that event by using the same way that we use to capture the click event we just need to give the same name that we have defined the in the child with the output okay it is the message event and now I will call a function whenever this event would be triggered we will call this function receive message and it will pass the event or whatever payload that we will pass from the child would be passed to this function receive message so we have to Define this receive message function as well so let's go to the TS file and in the app component TS file I will Define it so here the message event syntax is how we listen for the message event emitted by the child component when this event occurs the receive message method in the parent component will be called so in the receive message function I will simply console the event or payload that we are receiving you can give it other name as well like message that's totally fine and here I will add a message received message from a child and concatenate it with the message variable or parameter so in this parent component the receive message method is defined to handle the message received from a child so for this example we will simply we are simply logging the message to the console so now let's open the console and here I will click on that you will see that the message is received from the child that is Hello from Child you can also display this message in the template file of the app component as well by adding a variable here that will store the message that will be received from the child so child data is equal to by default it is empty but you can save the message from the child and save it in the child data property and then you can go back to the HTML and here here you can simply add it like uh child data okay by default uh it is empty so that is not visible but as soon as you click on that the message from the child would be visible immediately and that's how output and event emitter work together to allow child components to communicate upwards to their parent components this forms a robust two-way Communication System between components in angular in our next next section we will look at practical application of these concepts by building a real world example now that we have a good grasp of input and output let's apply these Concepts to a real world scenario imagine we are building an online store where users can select products and view their details we will use input to pass product information to a detail view component and output to send a message back to the parent component when a user adds a product to their card so let's start by creating two components a product list and a product detail view okay both of these components have been generated as you can see in the sidebar now in the product list component we will have an array of the products each product will have properties like name description and price so let's do that so first of all I will Define a property with an array of objects that will have property name price and description now we will use the product detail company to display the details of a selected product we will use the input decorator to pass the selected product to this component so let's go to the product detail. component.ts file and here I will Define the input and give it the name product so in the product list components template we will list each product and and pass the selected product to the product detail component using input now let's go back to the product list component. HTML file actually as we want to use the product detail in the product list component I need to import that product detail component in the Imports array now I can easily add the app product detail here and I will wrap it in the for Loop okay and here I will add product of products uh yes [Music] and all right uh you can also Track by the ID as well if there is an ID available in your object like ID one ID 2 and ID3 so then you can simply do that product by product. ID okay now we will pass the product product in the product detail component in this way okay so next let's handle the adding a product to the cart we'll use the output decorator in the product detail to emit an event when the add to cart button is clicked so let's open the product detail component. HTML dots actually and here I will add an output and here I will add add to Cod is equal to new event emitter okay now I will Define a function here on add to Cod and we will emit the event from this function in this prod product detail components template we will add a button that calls on add to cart when clicked so let's go back to the product detail component and here I will add a button and here I will add add two cart button and let's register The Click event and that will call the on add to cart function we will also need to display the information of the product as this component is supposed to have the details of the product so let's add that uh so we have product name product price and description and here we are using the built-in currency pipe of angular so now let's uh finally the product list component now finally in the product list component we will listen for the add to cart event and Implement a method to handle it so let's go to the product list. component. HTML and here I will add an event add to cart and now I will call a function on product added to cart and I will pass it the event that would be the product in our case now I will Define this function in the TS file and this will be receiving the product from the parameter and now I will simply display the product name in the console okay so now we need to display the product list in the app component so let's go to the app component and import the product list component in the Imports array and go back to the app component. HTML and let's remove thing and this time I will add app products list and you will see that we have a list of products let me remove the default text that product list works from here okay now you can see that we have three products being listed here and let's open the inspect element console and here in the console as soon as I click on this let's SP let's say we have phone mini and if I click on the add to cart you will see that in the console it is saying that phone mini was added to the card and it is happening because of this function okay so you can also collect these uh products somewhere maybe you have a property a variable Cod items is equal to by default it would be an empty array and let me Define the Cod items array in the product list by default it would be would be an empty array and whenever a item would be added to the cart we will simply push that item or product in the cart items areay so this is actually very basic and simple example just to give you basic understanding how things works but in the real world and real project you may be using some more advanced uh ways to handle your code like maybe you will have a service where you will manage your cart items or something whatever you prefer now somewhere here on the top right I will display the number of items in the card here so here I will use the card items. length property that will give us the number of the items items in the card okay so you can style it if you want to like font weight bold okay so now if you add this thing in the card it will be added in the card okay you can see that counter is also being updated and there you have it a simple online store where the products are listed details are displayed using input and actions are communicated back to the parent component using output this example illustrates how these decorators can be effectively used in real world applications next we will look into some best practices so after exploring input and output through a practical example let's discuss some best practices to make the most of of out of these features following these guidelines will help you build more efficient and maintainable angular applications so very first best practice is using strong typing always Define clear types for your input and output properties this improves the readability and helps to catch errors during the compile time so for example let's go back to our component where we have defined the input somewhere so I'm going to the product detail DS and here we have the input right now I added the any so instead of using any we should have used the type product interface and right now it is not defined but in the real world you will define an interface something like that interface product and within that you will specify the format of your product and in this way you can add a type to your input next best practice is to keep components independent and reusable so design your components to be as independent as possible avoid creating tight coupling between parent and child components this increases reusability and makes your component more modular next best practice is to use output for events only remember output should be used for the event communication not for passing data like input it's about letting the parent component know that something happened in the child component next one is Li Li MIT the number of inputs and outputs having too many input and outputs properties can make your component complex and hard to maintain strive for simpler interface with fewer inputs and outputs next is avoid complex object manipulation be cautious when passing objects as input avoid manipulating these objects directly as it can lead to unexpected behavior and makes your code harder to debug so so always try to manipulate the object from the parent instead of manipulating them from the child next one is initialize input properties it's good practice to initialize input properties to prevent undefined errors you can set default values or use optional chaining in your template so for example here I added the question mark here so if you uh don't have the question mark and you you may want to add the initialize it as well with a default value so it's totally up to you next we will talk about some common mistakes and discuss how to avoid them first one is mutating input data a common mistake is directly modifying the data received via input this can create unpredictable results due to angular's change detection and mechanism instead use immutable data patterns or deep copy objects before modification next common mistake is overusing event emitter with output so another Pitfall is overusing the event emitter for non-event related communication remember output should be used primarily for notifying the parent component about events not as the method for data binding next one is neglect neglecting life cycle hooks for input data when using input it's important to handle data changes correctly use life cycle hooks like NG on changes to react to input property changes especially if the reaction involves complex logic or side effects next one is creating circular dependences be careful not to create circular dependences between components with input and output this can lead to an endless loop and performance issues by keeping these best practices and common pit Falls in your mind you can leverage input and output more effectively making your angular applications robust maintainable and scalable with a solid understanding of basics of input and output it's time to delve into some Advanced Techniques and Concepts this will help you to manage more complex scenarios and optimize your angular application for better performance and and scalability first Advanced Techniques in component communication is nested component Communication in complex applications you might have multiple levels of nested components managing communication between them can be challenging one approach is to use combination of input and output to pass data down and up the component Tre however for deeply nested structures consider using angular services or State Management libraries to maintain sanity in your code base when it comes to Performance be mindful of how often your data changes and how these changes propagate through your components use strategies like on push change detection to reduce unnecessary checks and be cautious with object mutations as they can trigger unexpected change detections now we will talk about some integration with other angular features so first one is working with Services services in angular are great way to manage and share data across components you can use services in conjunction with input and output for more complex communication patterns for example a service can act as a data store with with components using output to send updates to service and input to receive data so for example uh let's suppose you are in a service so here you will have a property private product source is equal to new Behavior subject okay and then you will have a current a variable current products this will save the product source as observable now let's suppose you are in a component and here you will use this do product product service do current product do subscribe and within that call back function of subscribe you will simply use this do selected product is equal to product and this is a product okay next you can also interact with directives angular directives can also interact with the with component properties for instance you can bind an input property to a directive to dynamically alter Its Behavior similarly directives can emit events that comp can listen to Via output so for example let's suppose you are in a directive and here you will Define input in this way okay and within that input you will set this. highlight and pass it the condition so here you using a Setter so as soon as an input was provided to this app highlight input we will take that input value we'll pass that value or condition to the Highlight fun function that may be in your directive or you can use condition yellow or [Music] transparent these Advanced Techniques and interactions showcase versatility and power of angular by mastering these you can build highly interactive efficient and scalable web applications as we wrap up this comprehensive guide on input and output in angular 17 let's quickly recap the main points we have covered we started with the basic of input and output understanding how they facilitate communication between parent child component we then set up angular 17 environment and Dove deeper into practical examples demonstrating how to use these decorators for dynamic component interactions we explored real world use cases delving into Advanced Techniques and interacting interaction with the other angular features remember mastering input and output is crucial for building interactive and dynamic web application these concepts are foundational in angular and understanding them will significantly enhance your development skills to continue your Learning Journey I recommend checking out the official angular documentation which is an excellent resource for more in-depth learning consider online courses on platforms like udmi or corsera and don't forget to join angular communities on platforms like stack Overflow or Reddit for real world tips and support I encourage you to practice what you have learned today try building your own applications using input and output and experiment with techniques we discussed if you found this tutorial helpful then please give it a thumbs up leave your comments below and don't forget to subscribe for more angular tutorials your support helps me create more content like this thank you so much for watching stay tuned for my next tutorials about angler until then Happy coding
Info
Channel: AyyazTech
Views: 4,309
Rating: undefined out of 5
Keywords: Angular 17, Angular Advanced Techniques, Angular Animations, Angular Best Practices, Angular Communication, Angular Community, Angular Component Interaction, Angular Data Security, Angular Debugging, Angular Development, Angular Directives, Angular Event Handling, Angular Framework Mastery, Angular Input Output, Angular Integrations, Angular Performance Optimizati, Angular Services, Frontend Development, Web Development
Id: MARuuQ23nus
Channel Id: undefined
Length: 28min 56sec (1736 seconds)
Published: Mon Dec 18 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.