Angular 2: Is there a way to bind a hashtag to a div?

狂风中的少年 提交于 2019-12-12 06:28:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!