使用“<ng-content>”时访问组件的值
Accessing the component's values when using `<ng-content>`
在使用 <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;
}
@ContentChild(PersonBoxComponent) box:PersonBoxComponent;
ngAfterContentInit() {
console.log(this.box);
}
在使用 <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;
}
@ContentChild(PersonBoxComponent) box:PersonBoxComponent;
ngAfterContentInit() {
console.log(this.box);
}