寻找一种在使用时访问组件值的方法<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;
}