I am trying to retrieve content projected by an angular component into a typescript variable.
I tried retrieving the content using @ViewChild decorator and display it using console log() but I get an error.
The following is the code I wrote in various files :
app.component.html (Parent Component)
<app-test>
<div class="t1">
Test Data 1
</div>
<div class="t2">
Test Data 2
</div>
</app-test>
test.component.html (Child Component)
<div #tt>The following data was passed to this component:</div>
<ng-content select=".t1" #t1></ng-content>
<ng-content select=".t2" #t1></ng-content>
test.component.ts (Child Component script)
import { Component, OnInit, ViewChildren, AfterContentInit, ElementRef }
from '@angular/core';
@Component({
selector: 'app-test',
templateUrl: './test.component.html',
styleUrls: [ './test.component.scss' ]
})
export class TestComponent implements AfterContentInit {
@ViewChildren('t1') t1: ElementRef;
@ViewChildren('t2') t2: ElementRef;
@ViewChildren('tt') tt: ElementRef;
constructor () { }
ngAfterContentInit() {
console.log(this.t1.nativeElement.innerHTML);
console.log(this.t2.nativeElement.innerHTML);
console.log(this.tt.nativeElement.innerHTML);
}
}
I get the following error running this code
AppComponent.html:1 ERROR TypeError: Cannot read property 'nativeElement' of undefined at TestComponent.push../src/app/test/test.component.ts.TestComponent.ngAfterContentInit (test.component.ts:16) at callProviderLifecycles (core.js:18847) at callElementProvidersLifecycles (core.js:18828) at callLifecycleHooksChildrenFirst (core.js:18818) at checkAndUpdateView (core.js:19749) at callViewAction (core.js:19986) at execComponentViewsAction (core.js:19928) at checkAndUpdateView (core.js:19751) at callWithDebugContext (core.js:20639) at Object.debugCheckAndUpdateView [as checkAndUpdateView] (core.js:20317)
My question is how can I display following:
The following data was passed to this component:
Test Data 1
Test Data 2
in the console safely ?