I have a my-alert-component
which looks like this:
import { Component, OnInit,Input } from '@angular/core';
@Component({
selector: 'app-my-alert',
template: `
<h1 (click)="alert()">{{type}}</h1>
<ng-content></ng-content>
`
})
export class MyAlertComponent implements OnInit {
@Input() type: string = "Success";
alert(){
console.log("alert");
}
constructor() { }
ngOnInit() {
}
}
And in my app
component, I am doing the following:
import { Component,ComponentRef,ComponentFactory,ViewContainerRef, ComponentFactoryResolver,ChangeDetectorRef, ViewChild, TemplateRef, ViewChildren, QueryList, AfterViewInit,ElementRef, ContentChild, AfterContentInit } from '@angular/core';
import { MyAlertComponent } from './my-alert.component';
@Component({
selector: 'app-root',
template: `
<app-my-alert>
<p #insideNgContentVar>A paragraph inside ng-content</p>
</app-my-alert>
<app-my-alert type="danger"></app-my-alert>
<app-my-alert type="success"></app-my-alert>
`
})
export class AppComponent implements AfterViewInit{
@ViewChildren(MyAlertComponent) alertComponents : QueryList<AlertComponent>;
@ContentChild('insideNgContentVar') insideNgContent:ElementRef;
ngAfterContentInit(){
console.log(this.insideNgContent.nativeElement.textContent);
}
ngAfterViewInit(){
this.alertComponents.forEach((alertComponentInstance) => console.log(alertComponentInstance));
}
}
This is pretty simple, I thought.
But the error I am getting is:
EXCEPTION: Error in :0:0 caused by: Cannot read property 'nativeElement' of undefined
What am I doing wrong?
EDIT
If in my-alert-component
I do:
@Component({
selector: 'app-my-alert',
template: `
<h1 (click)="alert()">{{type}}</h1>
<ng-content></ng-content>
`
})
export class MyAlertComponent implements AfterContentInit,AfterViewInit {
@Input() type: string = "Success";
@ContentChild('insideNgContent') insideNgContentRef:ElementRef;
alert(){
console.log("alert");
}
ngAfterContentInit(){
console.log(this.insideNgContentRef.nativeElement.textContent);
}
And in my app
component:
template: `
<app-my-alert>
</app-my-alert>
<app-my-alert type="danger">
<p #insideNgContent>A paragraph inside ng-content</p>
</app-my-alert>
<app-my-alert type="success"></app-my-alert>
`
After these changes also, something seems to be missing.
What is that?