1

寻找一种在使用时访问组件值的方法<ng-content>

import {Component} from '@angular/core';

@Component({
  selector: 'home-page',
  template: `<person-box>{{name}}</person-box> <!-- something like this -->`
})
export class HomePageComponent {
  // missing code?
}

组件代码:

import {Component} from '@angular/core';

@Component({
  selector: 'person-box',
  template: `<div style="background-color: blue;"><ng-content></ng-content></div>`
})
export class PersonBoxComponent {
  name = 'Katharina Muster';
}

(上面的例子当然非常简化。)


使用@ViewChild时有效:

import {Component} from '@angular/core';

@Component({
  selector: 'home-page',
  template: `<person-box>{{box.name}}</person-box>`
})
export class HomePageComponent {
  @ViewChild(PersonBoxComponent) box: PersonBoxComponent;
}
4

1 回答 1

3
@ContentChild(PersonBoxComponent) box:PersonBoxComponent;

ngAfterContentInit() {
  console.log(this.box);
}
于 2017-03-08T09:27:56.517 回答