用处
可以随意调整组件显示的位置,个人觉得在嵌套组件中最方便
举例
app.component.ts
import { Component, ViewChild, TemplateRef,ViewContainerRef } from '@angular/core';
@Component({
selector: 'app-root',
styleUrls: ['./app.component.css'],
template: `
<div>
<app-parent>
<app-child></app-child>
</app-parent>
</div>
`
})
export class AppComponent {
}
parent.component.ts
import { Component, OnInit, TemplateRef } from '@angular/core';
interface Ichild extends Component{
content: TemplateRef<void>
}
@Component({
selector: 'app-parent',
styleUrls: ['./parent.component.css'],
template: `
<div>
<div *ngIf="position==true">
<ng-template [ngTemplateOutlet]="myChild.content"></ng-template>
</div>
<div><button (click)="change()">btn</button></div>
<div *ngIf="position==false">
<ng-template [ngTemplateOutlet]="myChild.content"></ng-template>
</div>
</div>
`
})
export class ParentComponent {
myChild: Ichild;
position: boolean = true;
addChild(child: Ichild) {
this.myChild = child;
}
change() {
this.position = !this.position;
}
}
child.component.ts
import { Component, OnInit, ViewChild, TemplateRef } from '@angular/core';
import { ParentComponent } from '../parent/parent.component';
@Component({
selector: 'app-child',
styleUrls: ['./child.component.css'],
template: `
<ng-template>
<div>
child component works!
</div>
</ng-template>
`
})
export class ChildComponent implements OnInit {
@ViewChild(TemplateRef) content: TemplateRef<void>;
constructor(public prt: ParentComponent) { }
ngOnInit() {
this.prt.addChild(this);
}
}