本文介绍了角度2:是否可以将主题标签绑定到div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建一个组件并将其注入。
I am creating a component and injecting it. Is there instead of having a static reference to the #theBody to have it bind from an array or variable?
import {ComponentRef, Injectable, Component, Injector, ViewContainerRef, ViewChild,ComponentResolver} from '@angular/core';
import { HeroListComponent } from './hero-list.component';
如果我像#theBody那样预定义了比我能够创建的
If I got like #theBody predefined than I able to created
@Component({
selector: 'my-app',
template: `<button (click)="addCmp()" >add</button>
<hero-list></hero-list>
<div #theBody ></div>
`,
directives: [HeroListComponent]
})
但是我想注入以便可以动态绑定组件创建。像这样的
But I would like to have injected so i could bind the component creation dynamically on the fly. So something like this
@Component({
selector: 'my-app',
template: `<button (click)="addCmp()" >add</button>
<hero-list></hero-list>
<div {{customtag}} ></div>
`,
directives: [HeroListComponent]
})
在customtag中定义#theBody的地方。
Where I define the #theBody in customtag.
export class AppComponent {
@ViewChild('theBody', {read: ViewContainerRef}) theBody;
cmp:ComponentRef;
customtag = '#theBody'
constructor(injector: Injector,private resolver: ComponentResolver) {
}
addCmp(){
console.log('adding');
this.resolver.resolveComponent(HeroListComponent).then((factory:ComponentFactory<any>) => {
this.cmp = this.theBody.createComponent(factory);
this.cmp.instance.test = "the test";
});
}
}
柱塞:
推荐答案
尝试这种方式:
<hero-list [customtag]='customtag'></hero-list>
在hero-list.component中:
And in hero-list.component:
export class HeroListComponent implements OnInit {
@Input() customtag: String;
constructor(private service: HeroService) { }
heroes: Hero[];
selectedHero: Hero;
test;
ngOnInit() {
this.heroes = this.service.getHeroes();
}
selectHero(hero: Hero) { this.selectedHero = hero; }
}
现在您可以在HTML中使用#theBody in hero页面。
now you can use in HTML your #theBody in hero page.
这篇关于角度2:是否可以将主题标签绑定到div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!