【问题标题】:Angular 2: Is there a way to bind a hashtag to a div?Angular 2:有没有办法将标签绑定到 div?
【发布时间】:2017-10-20 19:45:32
【问题描述】:

我正在创建一个组件并注入它。是否有一个对#theBody 的静态引用而不是让它从数组或变量中绑定?

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]
})

我在 customtag 中定义#theBody。

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

【问题讨论】:

    标签: angular data-binding components


    【解决方案1】:

    试试这个方法:

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

    在 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。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-25
    • 2012-07-07
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2010-12-19
    • 2022-01-22
    • 1970-01-01
    相关资源
    最近更新 更多