#31 ViewChild() in Angular | Angular Component & Directives | A Complete Angular Course

#31 ViewChild() in Angular | Angular Component & Directives | A Complete Angular Course

Understanding ViewChild Decorator in Angular

Introduction to Template Reference Variables

  • The lecture begins with a recap of template reference variables, which store references to DOM elements, components, or directives.
  • The focus shifts to the ViewChild decorator, which is used to query and obtain a reference to a DOM element within a component.

Practical Example of ViewChild

  • An example is introduced using the search component's HTML file that contains an input element with a template reference variable.
  • A button element is included; when clicked, it triggers the updateSearchText method while passing the template reference variable as an argument.

Accessing DOM Elements Without Events

  • The current setup requires clicking the button before accessing the input element. However, there’s a need for immediate access upon loading the component.
  • The speaker suggests removing event-based parameters from methods to allow direct access to DOM elements as soon as the component loads.

Implementing ViewChild Decorator

  • A new property named searchInputElement is created in the class to store a reference to the input element.
  • This property is decorated with @ViewChild, requiring an import from Angular core. It takes two parameters: one mandatory (selector), and one optional.

Using ViewChild Effectively

  • To select the input element using its template reference variable name, it’s passed as a string into @ViewChild.
  • The type of searchInputElement can be specified as ElementRef, also requiring an import from Angular core for proper usage.

Updating Search Functionality

  • In place of using method parameters for input elements, now directly utilize searchInputElement within methods.
  • After implementing these changes, functionality remains intact; typing in the search box and clicking results in expected behavior without needing parameter passing.

Key Takeaways on ViewChild Usage

  • The @ViewChild decorator queries and retrieves only the first matching DOM element based on provided selectors.

Understanding ViewChild Decorator in Angular

Overview of ViewChild Decorator

  • The ViewChild decorator is used to access the first matching element based on a template reference variable. It returns a reference to that element.
  • The ViewChild decorator accepts an optional second argument, which can include properties like read and static.

Properties of the Second Argument

  • The read property allows reading different tokens from the required elements, while the static property determines when the query should be resolved.
  • By default, the static property is set to true, meaning queries are resolved as soon as the view initializes. If set to false, resolution occurs only after each change detection cycle.

Change Detection Cycle

  • If you want immediate assignment of a view child property, keep the static property true or omit it. Setting it to false delays assignment until after change detection cycles.
  • Understanding how and when references are assigned is crucial for managing component interactions effectively.

Passing Data Between Sibling Components

Context of Component Interaction

  • In a container component with sibling components (product list and product detail), passing data between them requires specific strategies since they lack direct parent-child relationships.

Methods for Data Passing

  • One method involves using custom event binding and output decorators in conjunction with input decorators to facilitate communication through their common parent (the container).
  • Another approach utilizes the ViewChild decorator to create a reference to one sibling component (product list), allowing access to its properties directly.

Implementation Steps

  • To pass data from product list to product detail via container:
  • Use custom event binding in product list to emit selected product changes.
  • Capture these changes in the container and pass them down as inputs to product detail.

Creating References with ViewChild

Establishing Component References

  • In the container component class, define a property for referencing another component (e.g., product list). This enables direct access once rendered on the page.

Importing Necessary Components

  • Ensure proper imports for any referenced components within your file structure. This step is essential for utilizing Angular's dependency injection effectively.

Understanding Component Interaction in Angular

Using Template Reference Variables and Selectors

  • The template reference variable from the container component can be used as a selector for initializing the product list component directly within the view template.
  • Instead of using a template reference variable, you can specify the component name (product list component) as a selector to initialize it.

Implementing ViewChild Decorator

  • To utilize the ViewChild decorator, it must be imported from Angular core. This allows storing a reference to the product list component in a property within the container component.
  • A new property named productListComp is created in the product detail component class to hold this reference, decorated with @Input() for binding.

Binding Properties Between Components

  • The @Input() decorator enables binding of properties to TypeScript expressions. The productListComp property will receive its value from the container component's property.
  • Property binding requires square brackets around the property name ([productListComp]) to assign it correctly from the container component.

Handling Undefined Values on Initialization

  • Initially, when no product is selected, accessing selectedProduct will result in an error since productListComp is undefined at that moment.
  • To avoid errors during initialization, set default values (e.g., undefined) and ensure that logic dependent on these properties runs after they are initialized.

Utilizing Lifecycle Hooks for Initialization

  • Angular lifecycle hooks allow executing logic at different stages of a component's lifecycle; specifically, ngOnInit is called after all properties are initialized.

Product Detail Component Implementation

Accessing Selected Product

  • The product list component is initialized with an instance of the product list component class, allowing access to its selected product property. This setup ensures that the application functions correctly by storing the selected product in the product detail component.

Utilizing String Interpolation

  • In the view template of the product detail component, string interpolation syntax is employed to dynamically display properties. Specifically, it accesses and displays the name property of the selected product instead of using hard-coded values.

Dynamic Display of Product Information

  • Upon selecting different products, their names are displayed correctly on the webpage. A refresh may be needed if any issues arise with displaying information or functionality (e.g., a non-working close button).

Binding Additional Properties

  • The next step involves replacing hard-coded values with dynamic bindings for other properties such as imageURL, gender, brand, and category. This enhances data representation within the application.

Conditional Rendering for Pricing

  • When displaying prices, both original and discounted prices are shown conditionally. If a product lacks a discounted price, that span should be hidden using Angular's *ngIf directive to manage visibility based on data availability.

Looping Through Arrays for Size and Color

  • To display sizes and colors associated with products, use *ngFor directives to loop through respective arrays (size and color). Each element should be rendered appropriately in the UI.

Dynamic Styling Based on Color Values

  • Instead of showing color names, implement dynamic styling that reflects actual color values from the array. This approach provides a more intuitive visual representation of available colors for each product.

Assignment for Further Learning

Video description

In this lecture you will learn about @ViewChild() in Angular and how to use it on DOM elements & Components. The @ViewChild() is a decorator which allows us to access a reference to a DOM element, a component or a directive in the component class. ASP.NET Core GitHub Repo: https://github.com/manojjha86/ASP.NET-Core-mvc NODE JS Course GitHub Repo: https://github.com/manojjha86/NODE-JS ANGULAR 16 Course GitHub Repo: https://github.com/manojjha86/angular-16-complete-course