Angular - Concepts
1. Selector:
In Angular, the selector is a property used to define how a component or directive is attached to the HTML view. The selector is specified inside the @Component
or @Directive
decorator and determines how the component or directive can be applied to the HTML DOM.
Types:
It can be defined as an element, attribute, or class selector.
Element Selector:
The component is used like a regular HTML element.
<app-root></app-root>
Attribute Selector:
The directive or component is applied to an HTML element as an attribute.
<div app-root></div>
Class Selector:
The directive or component is applied when a certain class is used on an element.
<div class="app-root"></div>
Multiple Selectors:
It’s possible to use multiple selectors to make a directive or component apply to different elements.
selector: '[appHighlight], div.appHighlight' })
({@ViewChild
:
@ViewChild
is a decorator in Angular used to access DOM element, directive, or child component in the view of the current component. This allows you to interact with child elements directly from the parent component class.
Scenarios:
Manipulating DOM elements, like focusing on an input field.
Calling methods or accessing properties of child components.
Modifying behavior or properties of directives applied to elements.
@ViewChildren
is a decorator in Angular that allows you to access multiple child elements, components, or directives in a parent component's view. It returns a QueryList
, a dynamic list of references that updates automatically when children are added or removed. Typically accessed in the ngAfterViewInit
lifecycle hook, it is commonly used to interact with multiple child components or elements, such as iterating over them or applying operations.
In summary, @ViewChildren
enables the parent component to efficiently interact with multiple children.
Example:
child.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-child',
template: `<p>Child component works!</p>`,
})
export class ChildComponent {
message = "Hello from Child Component";
}
@ViewChildren(ChildComponent): Gets references to all
instances of ChildComponent in the template, returning a live QueryList of
child components.
QueryList: A dynamic collection that can be iterated
to access each child component's properties.
ngAfterViewInit: Allows access to the child
components after the view is initialized, ensuring the components are rendered
first.
accessChildren method: Iterates over the QueryList
and logs each child's message property when the button is clicked.
Comments
Post a Comment