2017-05-20 3 views
0

私はコンポーネントを作成し、それを注入しています。 #theBodyへの静的な参照が配列や変数からバインドされるのではなく、そこにありますか?角2:ハッシュタグをdivにバインドする方法はありますか?

import {ComponentRef, Injectable, Component, Injector, ViewContainerRef, ViewChild,ComponentResolver} from '@angular/core'; 
import { HeroListComponent } from './hero-list.component'; 

私は#theBodyように、私ができるよりも、事前に定義されてしまった場合は、

@Component({ 
    selector: 'my-app', 
    template: `<button (click)="addCmp()" >add</button> 
    <hero-list></hero-list> 
    <div #theBody ></div> 
    `, 
    directives: [HeroListComponent] 
}) 

を作成しましたが、私はその場で動的コンポーネントの作成を結合することができるので、私は、注入されているしたいと思います。だからこのようなもの

@Component({ 
    selector: 'my-app', 
    template: `<button (click)="addCmp()" >add</button> 

    <hero-list></hero-list> 

    <div {{customtag}} ></div> 
    `, 
    directives: [HeroListComponent] 
}) 

ここでは、#theBodyを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

この方法を試してみてください:

<hero-list [customtag]='customtag'></hero-list> 

主人公-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を使用することができますヒーローページ。

+0

は、私はあなたが提案し何をしようとした{ヒーロー-list.component.tsに必要な追加の入力I'ts 'インポートエラー https://plnkr.co/edit/RuwvwBOMK2IOXrhBQNPe?p=preview –

+0

を取得しましたコンポーネント、OnInit、入力} '@ angle/core'; ' – Dekonunes

+0

真、更新されたピンクhttps://plnkr.co/edit/RuwvwBOMK2IOXrhBQNPe?p=preview –

関連する問題