The ngAfterViewInit
lifecycle hook isn't triggered for a Component that is transcluded into another component using <ng-content>
, as shown below:
<app-container [showContent]="showContentContainer">
<app-input></app-input>
</app-container>
However, everything works fine without <ng-content>
:
<app-input *ngIf="showContent"></app-input>
The container component is described as:
@Component({
selector: 'app-container',
template: `
<ng-container *ngIf="showContent">
<ng-content></ng-content>
</ng-container>
`
})
export class AppContainerComponent {
@Input()
showContentContainer = false;
@Input()
showContent = false;
}
The input component is defined as:
@Component({
selector: 'app-input',
template: `<input type=text #inputElem />`
})
export class AppInputComponent implements AfterViewInit {
@ViewChild("inputElem")
inputElem: ElementRef<HTMLInputElement>;
ngAfterViewInit() {
console.info("ngAfterViewInit has been executed!");
this.inputElem.nativeElement.focus();
}
}
Check out a live example here: https://stackblitz.com/edit/angular-playground-vqhjuh