如何在angular4中使用TemplateRef的createEmbeddedView方法?
How to use createEmbeddedView method of TemplateRef in angular4?
我开始学习 DOM 在 Angular 中的操作并注意 templateRef 及其方法 createEmbeddedView。我更好奇地了解这种方法。现在我所有的问题是,如何使用此方法的 createEmbeddedView
@Component({
selector: 'app-root',
template: `
<ng-template #template>
</ng-template>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
constructor() { }
ngAfterViewChecked() {
this._template.createEmbeddedView('this is a embedded view')
}
}
您可以使用 createEmbeddedView
方法创建嵌入视图,然后通过 ViewContainerRef
:
将该视图附加到 DOM
@Component({
selector: 'app-root',
template: `
<ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
<ng-container #vc></ng-container>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor() { }
ngAfterViewChecked() {
const view = this._template.createEmbeddedView({fromContext: 'John'});
this.vc.insert(view);
}
}
或者您可以直接使用 ViewContainerRef
创建视图:
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}
上下文是一个具有属性的对象,您可以通过 let-
绑定访问这些属性。
要了解更多信息,请阅读 Exploring Angular DOM manipulation techniques using ViewContainerRef and also see this answer。
我开始学习 DOM 在 Angular 中的操作并注意 templateRef 及其方法 createEmbeddedView。我更好奇地了解这种方法。现在我所有的问题是,如何使用此方法的 createEmbeddedView
@Component({
selector: 'app-root',
template: `
<ng-template #template>
</ng-template>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
constructor() { }
ngAfterViewChecked() {
this._template.createEmbeddedView('this is a embedded view')
}
}
您可以使用 createEmbeddedView
方法创建嵌入视图,然后通过 ViewContainerRef
:
@Component({
selector: 'app-root',
template: `
<ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
<ng-container #vc></ng-container>
`
})
export class AppComponent implements AfterViewChecked {
@ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
@ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
constructor() { }
ngAfterViewChecked() {
const view = this._template.createEmbeddedView({fromContext: 'John'});
this.vc.insert(view);
}
}
或者您可以直接使用 ViewContainerRef
创建视图:
ngAfterViewChecked() {
this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
}
上下文是一个具有属性的对象,您可以通过 let-
绑定访问这些属性。
要了解更多信息,请阅读 Exploring Angular DOM manipulation techniques using ViewContainerRef and also see this answer。