-
-
Save mbao01/2c8817819624ef2c46e983b98b99024d to your computer and use it in GitHub Desktop.
Angular 2.x - Template Outlet vs Content Projection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component({ | |
selector: 'app', | |
template: ` | |
<h1>Angular's content projection and lifecycle example</h1> | |
<app-content> | |
<app-nested-component></app-nested-component> | |
</app-content> | |
`, | |
}) | |
export class App {} | |
@Component({ | |
selector: 'app-content', | |
template: ` | |
<button (click)="display = !display">Toggle content</button> | |
<ng-content *ngIf="display"></ng-content> | |
`, | |
}) | |
export class Content { | |
display = false; | |
} | |
@Component({ | |
selector: 'app-nested-component', | |
template: `<b>Hello World!</b>`, | |
}) | |
export class NestedComponent implements OnDestroy, OnInit { | |
ngOnInit() { | |
alert('app-nested-component initialised!'); | |
} | |
ngOnDestroy() { | |
alert('app-nested-component destroyed!'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Component({ | |
selector: 'app', | |
template: ` | |
<h1>Angular's template outlet and lifecycle example</h1> | |
<app-content [templateRef]="nestedComponentRef"></app-content> | |
<template #nestedComponentRef> | |
<app-nested-component></app-nested-component> | |
</template> | |
`, | |
}) | |
export class App {} | |
@Component({ | |
selector: 'app-content', | |
template: ` | |
<button (click)="display = !display">Toggle content</button> | |
<template | |
*ngIf="display" | |
[ngTemplateOutlet]="templateRef"> | |
</template> | |
`, | |
}) | |
export class Content { | |
display = false; | |
@Input() templateRef: TemplateRef; | |
} | |
@Component({ | |
selector: 'app-nested-component', | |
template: ` | |
<b>Hello World!</b> | |
`, | |
}) | |
export class NestedComponent implements OnDestroy, OnInit { | |
ngOnInit() { | |
alert('app-nested-component initialized!'); | |
} | |
ngOnDestroy() { | |
alert('app-nested-component destroyed!'); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template [ngTemplateOutlet]="exampleTemplateRef"></template> | |
<template #exampleTemplateRef> | |
<b>Example template<b> | |
</template> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment