问题
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';
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]
})
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";
});
}
}
Plunker: https://plnkr.co/edit/RuwvwBOMK2IOXrhBQNPe?p=preview
回答1:
Try this way:
<hero-list [customtag]='customtag'></hero-list>
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; }
}
now you can use in HTML your #theBody in hero page.
来源:https://stackoverflow.com/questions/44091044/angular-2-is-there-a-way-to-bind-a-hashtag-to-a-div