{"id":744,"date":"2018-02-07T03:55:00","date_gmt":"2018-02-07T03:55:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=744"},"modified":"2025-02-18T14:43:37","modified_gmt":"2025-02-18T14:43:37","slug":"viewchild-and-contentchild-angular","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/viewchild-and-contentchild-angular","title":{"rendered":"What Is ViewChild and ContentChild in Angular?"},"content":{"rendered":"\n<p>ViewChild and ContentChild in Angular are used for component communication. For example, if parent\u00a0<a href=\"\/products\/ignite-ui-angular\">Angular components<\/a>\u00a0want access to child components, they use ViewChild or ContentChild.<\/p>\n\n\n\n<p>In this blog post, then, we will explain the essence of Angular ViewChild and Angular ContentChild and show you how to use them in your app.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-viewchild-in-angular\">What Is ViewChild in Angular<\/h2>\n\n\n\n<p><span class=\"TextRun SCXW35067563 BCX0\" lang=\"EN-US\"><span class=\"NormalTextRun SpellingErrorV2Themed SCXW35067563 BCX0\">Angular ViewChild<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> or <\/span><span class=\"NormalTextRun SpellingErrorV2Themed SCXW35067563 BCX0\">ViewChildren<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> decorators are used to get reference to a <\/span><span class=\"NormalTextRun SCXW35067563 BCX0\">component<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> instance by querying the template using the <\/span><span class=\"NormalTextRun SCXW35067563 BCX0\">component<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> reference name or class name.<\/span> <span class=\"NormalTextRun SpellingErrorV2Themed SCXW35067563 BCX0\">ViewChild<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\">&nbsp;in Angular returns the first matching <\/span><span class=\"NormalTextRun SCXW35067563 BCX0\">component<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> and <\/span><span class=\"NormalTextRun SpellingErrorV2Themed SCXW35067563 BCX0\">ViewChildren<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> returns all the matching components as a <\/span><span class=\"NormalTextRun SpellingErrorV2Themed SCXW35067563 BCX0\">QueryList<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> of items. We can use these references to work with the <\/span><span class=\"NormalTextRun SCXW35067563 BCX0\">component<\/span><span class=\"NormalTextRun SCXW35067563 BCX0\"> class or its DOM element.<\/span><\/span><span class=\"EOP SCXW35067563 BCX0\">&nbsp;<\/span><\/p>\n\n\n\n<p>If you want to access the following inside the Parent Component, use @ViewChild decorator in Angular.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"using-messagecomponent\">Using MessageComponent<\/h3>\n\n\n\n<p>Let&#8217;s assume that we have a MessageComponent as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component, Input } from \"@angular\/core\";\n@Component({\n    selector: \"app-message\",\n    template: `&lt;h2>{{message}}&lt;\/h2>`,\n})\nexport class MessageComponent {\n    @Input() message: string;\n}\n<\/pre>\n\n\n\n<p>We are using MessageComponent inside AppComponent as shown in here:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component, OnInit } from \"@angular\/core\";\n@Component({\n    selector: \"app-root\",\n    template: ` &lt;div>\n        &lt;h1>Messages&lt;\/h1>\n        &lt;app-message [message]=\"message\">&lt;\/app-message>\n    &lt;\/div>`,\n})\nexport class AppComponent implements OnInit {\n    message: any;\n    ngOnInit() {\n        this.message = \"Hello World !\";\n    }\n}\n<\/pre>\n\n\n\n<p>The MessageComponent will be located inside the template of&nbsp;AppComponent. Therefore, we can access it as a ViewChild.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">export class AppComponent implements OnInit, AfterViewInit {\n    message: any;\n    @ViewChild(MessageComponent) messageComponent: MessageComponent;\n\n    ngAfterViewInit() {\n        console.log(this.messageComponent);\n    }\n\n    ngOnInit() {\n        this.message = \"Hello World !\";\n    }\n}\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"changing-the-value-of-messagecomponent\">Changing The Value of MessageComponent<\/h3>\n\n\n\n<p>Now, let&#8217;s try to change the value of the MessageComponent property.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ngAfterViewInit() {\n   console.log(this.messageComponent);\n   this.messageComponent.message = 'Passed as View Child';\n}<\/pre>\n\n\n\n<p>Here, we are changing the value of the ViewChild property.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"viewchild-and-querylist\">Working With Angular ViewChildren and QueryList<\/h3>\n\n\n\n<p>We are using MessageComponent inside a *ngFor directive; hence, there are multiple references to MessageComponent. We can access it now as ViewChildren and QueryList, as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@ViewChildren(MessageComponent) messageComponent: QueryList&lt;MessageComponent>;\n   ngAfterViewInit() {\n    console.log(this.messageComponent);\n   }<\/pre>\n\n\n\n<p>In the output, you will get various references of MessageComponent as ViewChildern.<\/p>\n\n\n\n<p>Now let us try to update the properties of ViewChildren as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ngAfterViewInit() {\n   console.log(this.messageComponent);\n   this.messageComponent.forEach((item) => { item.message = 'Infragistics'; });\n}<\/pre>\n\n\n\n<p>As you see, we are iterating through each item of Angular ViewChildren and updating each property. This will update the property value but again, you will get the error, \u201c<strong>Expression has changed after it was last checked.\u201d<\/strong><\/p>\n\n\n\n<p>You can fix it by manually calling change detection like ViewChild. Keep in mind that we do not have ViewChildren reference available in AfterContentInit life cycle hook. You will get <strong>undefined<\/strong> in ngAfterContentInit() life cycle hook for ViewChildren reference as shown in the listing below : &nbsp;<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ngAfterContentInit() {\n   console.log(this.messageComponent); \/\/ undefined \n}<\/pre>\n\n\n\n<p>However, you can manually call change detection to fix error:&nbsp; \u201c<strong>Expression has changed after it was last checked\u201d<\/strong><\/p>\n\n\n\n<p><strong>&nbsp;<\/strong>To use a change detection mechanism<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Import ChangeDetectorRef from @angular\/core<\/li>\n\n\n\n<li>Inject it to the constructor of Component class<\/li>\n\n\n\n<li>Call detectChanges() method after ViewChild property is changed<\/li>\n<\/ol>\n\n\n\n<p>You can use a manual change detection like shown in below listing:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">@ViewChildren(MessageComponent) messageComponent: QueryList&lt;MessageComponent>;\n\tconstructor(private cdr: ChangeDetectorRef) {\n}\nngAfterViewInit() {\n\tconsole.log(this.messageComponent);\n\tthis.messageComponent.forEach((item) => { item.message = 'Infragistics'; });\n\tthis.cdr.detectChanges();\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"what-is-contentchild-in-angular\">What is ContentChild in Angular?<\/h2>\n\n\n\n<p>The Angular ContentChild property decorator is very similar to the ViewChild and again provides a powerful way to interact with and manipulate projected content within a component. Using it, you can easily get the reference to the Projected Content in the DOM.<\/p>\n\n\n\n<p>Let us start with understanding about ContentChild. Any element that is located inside the template is ContentChild.<\/p>\n\n\n\n<p>To understand it, let&#8217;s consider MessageContainerComponent.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component } from \"@angular\/core\";\n@Component({\n    selector: \"app-messagecontainer\",\n    template: ` &lt;div>\n        &lt;h3>{{greetMessage}}&lt;\/h3>\n        &lt;ng-content select=\"app-message\">&lt;\/ng-content>\n    &lt;\/div>`,\n})\nexport class MessageContainerComponent {\n    greetMessage = \"Ignite UI Rocks!\";\n}<\/pre>\n\n\n\n<p>In this component, we are using Angular Content Projection.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"passing-messagecomponent\">Passing MessageComponent in Angular ContentChild<\/h3>\n\n\n\n<p>Any element or component projected inside &lt;ng-content&gt; becomes a ContentChild. If you want to access and communicate with MessageComponent projected inside MessageContainerComponent, you need to read it as a ContentChild.<\/p>\n\n\n\n<p>Before we go ahead and learn to use ContentChild in Angular, first check out how MessageContainerComponent is used and how is MessageComponent is projected,<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component, OnInit } from \"@angular\/core\";\n@Component({\n    selector: \"app-root\",\n    template: ` &lt;div>\n        &lt;app-messagecontainer>\n            &lt;app-message [message]=\"message\">&lt;\/app-message>\n        &lt;\/app-messagecontainer>\n    &lt;\/div>`,\n})\nexport class AppComponent implements OnInit {\n    message: any;\n    ngOnInit() {\n        this.message = \"Hello World !\";\n    }\n}\n<\/pre>\n\n\n\n<p>As you can see in the listing above, we use MessageContainerComponent in the AppComponent and pass MessageComponent to be projected inside it. Since MessageComponent is used in MessageContainerComponent with content projection, it becomes Angular ContentChild.<\/p>\n\n\n\n<p>Since MessageComponnet is projected and being used inside the template of MessageContainerComponent, it can be used as ContentChild, as shown below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component, ContentChild, AfterContentInit } from \"@angular\/core\";\nimport { MessageComponent } from \".\/message.component\";\n\n@Component({\n    selector: \"app-messagecontainer\",\n    template: ` &lt;div>\n        &lt;h3>{{greetMessage}}&lt;\/h3>\n        &lt;ng-content select=\"app-message\">&lt;\/ng-content>\n    &lt;\/div>`,\n})\nexport class MessageContainerComponent implements AfterContentInit {\n    greetMessage = \"Ignite UI Rocks!\";\n    @ContentChild(MessageComponent) MessageComponentContentChild: MessageComponent;\n    ngAfterContentInit() {\n        console.log(this.MessageComponentContentChild);\n    }\n}<\/pre>\n\n\n\n<p>We need to do the following tasks:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Import ContentChild and AfterContentInit from @angular\/core.<\/li>\n\n\n\n<li>Implement AfterContentInit life cycle hook to component class.<\/li>\n\n\n\n<li>Create a property with decorator @ContentChild.<\/li>\n\n\n\n<li>Access that inside ngAfterContentInit life cycle hook.<\/li>\n<\/ol>\n\n\n\n<p>You can modify the ContentChild property inside the ngAfterContentInit life cycle hook of the component. Let&#8217;s assume that there is more than one MessageComponent projected as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">import { Component, OnInit } from \"@angular\/core\";\n@Component({\n    selector: \"app-root\",\n    template: ` &lt;div>\n        &lt;app-messagecontainer>\n            &lt;app-message *ngFor=\"let m of messages\" [message]=\"m\">&lt;\/app-message>\n        &lt;\/app-messagecontainer>\n    &lt;\/div>`,\n})\nexport class AppComponent implements OnInit {\n    messages: any;\n    ngOnInit() {\n        this.messages = this.getMessage();\n    }\n    getMessage() {\n        return [\"Hello India\", \"Which team is winning Super Bowl? \", \"Have you checked Ignite UI ?\", \"Take your broken heart and make it to the art\"];\n    }\n}\n<\/pre>\n\n\n\n<p>Now we have more than one ContentChild, so we need to access them as ContentChildren as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">export class MessageContainerComponent implements AfterContentInit {\n    greetMessage = \"Ignite UI Rocks!\";\n    @ContentChildren(MessageComponent) MessageComponentContentChild: QueryList&lt;MessageComponent>;\n    ngAfterContentInit() {\n        console.log(this.MessageComponentContentChild);\n    }\n}<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"contentchild-and-querylist\">Working With ContentChildren and QueryList<\/h3>\n\n\n\n<p>To work with ContentChildren and QueryList, you need to do following tasks:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Import ContentChildren , QueryList , AfterContentInit from @angular\/core.<\/li>\n\n\n\n<li>Create a property with decorator @ContentChildren with type QueryList.<\/li>\n\n\n\n<li>Access ContentChildren reference in ngAfterContentInit() life cycle hook.<\/li>\n<\/ol>\n\n\n\n<p>You can query each item in ContentChildren and modify the property as like this:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">ngAfterContentInit() {\n   this.MessageComponentContentChild.forEach((m) => m.message = 'Foo');\n}<\/pre>\n\n\n\n<p>And this is how&nbsp;you can work with ContentChildren in Angular.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"wrap-up\">Wrap Up<\/h2>\n\n\n\n<p>ViewChild and ContentChild are two very important features of Angular. They are used to enable access to the Child Component in the Parent Component. Any directive, component, and element that is part of the component template is accessed as ViewChild. On the other hand,&nbsp;any element or component that is projected inside &lt;ng-content&gt; is accessed as ContentChild.<\/p>\n\n\n\n<p>To simplify ViewChild and ContentChild in Angular even more, you can try our full-featured <a href=\"\/products\/ignite-ui-angular\/angular\/components\/general\/cli\/getting-started-with-angular-schematics\">Ignite UI for Angular components library<\/a>. It provides the fastest Angular data grid and 60+ high-performance charts, empowering you to build modern-day, high-performance Angular apps easily.<\/p>\n\n\n\n<p><span style=\"font-size: 75%;\">(Last Updated: 08.09.2023)<\/span><\/p>\n\n\n\n<figure class=\"wp-block-image\"><a href=\"\/products\/ignite-ui-angular\/download\"><img decoding=\"async\" src=\"https:\/\/static.infragistics.com\/marketing\/Blog-in-content-ads\/Ignite-UI-Angular\/ignite-ui-angular-you-get-ad.gif\" alt=\"Ignite UI for Angular\"\/><\/a><\/figure>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This blog shows how Angular ViewChild and ContentChild let you access and manipulate child components and DOM elements within a component&#39;s view. Read all.<\/p>\n","protected":false},"author":65,"featured_media":1282,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7],"tags":[],"class_list":["post-744","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/744","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=744"}],"version-history":[{"count":11,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/744\/revisions"}],"predecessor-version":[{"id":1908,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/744\/revisions\/1908"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/1282"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=744"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=744"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=744"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}