Skip to content

Instantly share code, notes, and snippets.

@mbao01
Forked from pietmichal/ContentProjection.ts
Created March 30, 2017 22:03
Show Gist options
  • Save mbao01/2c8817819624ef2c46e983b98b99024d to your computer and use it in GitHub Desktop.
Save mbao01/2c8817819624ef2c46e983b98b99024d to your computer and use it in GitHub Desktop.
Angular 2.x - Template Outlet vs Content Projection
@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!');
}
}
@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!');
}
}
<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