In Angular, both
@ViewChild
and @ContentChild
decorators are used to access child components or elements within a parent component. However, they differ in terms of the scope in which they operate.@ViewChild
:@ViewChild
is used to access child components or DOM elements that are projected or declared within the template of the parent component.- It can only access elements that are part of the component's own template, not elements projected from the parent or sibling components.
@ViewChild
can query elements using a template reference variable or a selector.- It returns a single instance of the queried element or component.
- Example usage:typescript@Component({ selector: 'app-parent', template: ` <app-child #childRef></app-child> ` }) export class ParentComponent { @ViewChild('childRef') childComponent: ChildComponent; }
@ContentChild
:@ContentChild
is used to access child components or DOM elements that are projected from the parent component into the content area of the child component.- It can access elements projected using Angular content projection mechanisms like
<ng-content>
. @ContentChild
can query elements using a template reference variable or a selector.- It returns a single instance of the queried element or component.
- Example usage:typescript@Component({ selector: 'app-child', template: ` <ng-content></ng-content> ` }) export class ChildComponent { @ContentChild('contentRef') contentElement: ElementRef; }html<app-child> <div #contentRef>Projected Content</div> </app-child>
In summary, @ViewChild
is used to access child components or elements within the template of the parent component, while @ContentChild
is used to access projected child components or elements within the content area of the child component.
Comments
Post a Comment