Angular 2:有没有办法将hashtag绑定到div?

时间:2017-05-20 21:37:05

标签: angular data-binding components

我正在创建一个组件并将其注入。是否存在对#theBody的静态引用以使其从数组或变量绑定?

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserStudent extends Model
{
    protected $table = 'user_student';

    function student()
    {
        return $this->hasOne('App\Student', 'id');
    }

    function agent()
    {
        return $this->belongsTo('App\Agent', 'id');
    }
}

如果我得到#theBody预定义而不是我能够创建

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

但是我想注入,所以我可以动态地绑定组件创建。像这样的东西

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

我在自定义标签中定义#theBody。

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

  <hero-list></hero-list>

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

Plunker:https://plnkr.co/edit/RuwvwBOMK2IOXrhBQNPe?p=preview

1 个答案:

答案 0 :(得分: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。