我正在关注《 Angular 5 Projects》一书中的一个教程,并对其中一个练习有疑问。
我不知道为什么必须实例化contentChild变量以及如何在代码中使用它。
ContentChild(CardComponent) contentChild: CardComponent;
有人可以解释一下吗?
下面是代码:
import { Component, ContentChild, AfterContentChecked } from '@angular/core';
@Component({
selector: 'card',
template: `
<ng-content></ng-content>
`,
styles: []
})
export class CardComponent {
}
@Component({
selector: 'app-root',
template: `
<card>{{card}}</card>
<button (click)="pickCard($event)">Pick a Card</button>
`,
styles: []
})
export class AppComponent implements AfterContentChecked {
card = CARD_ACE_OF_SPADES;
@ContentChild(CardComponent) contentChild: CardComponent;
ngAfterContentChecked() {
console.log("content inside card has been checked: " + this.card);
}
pickCard()
{
this.card = this.card === CARD_ACE_OF_SPADES ? CARD_TEN_OF_CLUBS :
CARD_ACE_OF_SPADES;
}
}
const CARD_ACE_OF_SPADES = 'ace of spades';
const CARD_TEN_OF_CLUBS = 'ten of clubs';
答案 0 :(得分:0)
应该是@ViewChild
。
ViewChild ==>直接在组件模板中使用的选择器。
ContentChild ==> <ng-content>
选择中使用的选择器。
例如:
@Component({
selector: 'first-comp',
template: `
<card1></card1>
<ng-conent></ng-content>
`
})
export class FirstComponent {
@ViewChild(Card1Component) card1: Card1Component;
@ContentChild(Card2Component) card2: Card2Component;
}
@Component({
selector: 'second-comp',
template: `
<first-comp>
<card2></card2>
</first-comp>
`
})
export class SecondComponent {
@ViewChild(FirstComponent) firstComp: FirstComponent;
@ViewChild(Card2Component) card2: Card2Component;
}