Pre*_*har 48 typescript angular
我想创建动态组件并将这些组件的视图插入到容器中.
我认为这可以通过ViewContainerRef来实现.
但我不知道,我们能得到ViewContainerRef任何组件吗?如果是的话怎么样?我是Angular的新手,如果有任何其他好的解决方案可以处理这种情况,请建议我.
更新 我认为,我非常接近解决方案.下面是代码.
app.component.ts
import {Component} from '@angular/core';
import {ContainerComponet} from './container.component'
@Component({
selector: 'my-app',
template: `
<container> </container>
`,
directives: [ContainerComponet]
})
export class AppComponent {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
container.component.ts
import {Component, ComponentResolver, ViewContainerRef} from '@angular/core'
import {controlBoxComponent as controlBox} from './controlBox.component';
@Component({
selector: 'container',
template: 'container'
})
export class ContainerComponet {
constructor(viewContainer: ViewContainerRef, private _cr: ComponentResolver) {
this._cr.resolveComponent(controlBox)
.then(cmpFactory => {
const ctxInjector = viewContainer.injector;
return viewContainer.createComponent(cmpFactory, 0, ctxInjector);
})
}
}
Run Code Online (Sandbox Code Playgroud)
controlBox.component.ts
import {Component} from '@angular/core'
@Component({
selector: 'controlBox',
template: 'controlBox'
})
export class controlBoxComponent {
constructor() { }
}
Run Code Online (Sandbox Code Playgroud)
产量
<my-app>
<container>container</container><controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</my-app>
Run Code Online (Sandbox Code Playgroud)
预期结果
<my-app>
<container>container
<controlbox _ngcontent-lsn-3="">controlBox</controlbox>
</container>
</my-app>
Run Code Online (Sandbox Code Playgroud)
Gün*_*uer 50
您可以通过ViewContainerRef当前组件视图中的元素获取当前组件
@Component({
selector: '...',
directives: [OtherComponent, FooComponent],
template: `
<other-component></other-component>
<foo-component #foo></foo-component>
<div #div></div>`
})
export class SomeComponent {
// `ViewContainerRef` from an element in the view
@ViewChild(OtherComponent, {read: ViewContainerRef}) other;
@ViewChild('foo', {read: ViewContainerRef}) foo;
@ViewChild('div', {read: ViewContainerRef}) div;
// `ViewContainerRef` from the component itself
constructor(private viewContainerRef:ViewContainerRef, private componentFactoryResolver: ComponentFactoryResolver) {}
let factory = this.componentFactoryResolver.resolveComponentFactory(ControlBox)
this.componentRef = this.other.createComponent(factory);
// this.componentRef = this.foo.createComponent(factory);
// this.componentRef = this.div.createComponent(factory);
// this.componentRef = this.viewContainerRef.createComponent(factory);
});
}
Run Code Online (Sandbox Code Playgroud)
另请参阅Angular 2动态选项卡,其中包含用户单击所选组件
| 归档时间: |
|
| 查看次数: |
47606 次 |
| 最近记录: |