Как переменная ContentChild используется в учебнике - PullRequest
0 голосов
/ 27 сентября 2018

Я следую учебному пособию из книги 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';

1 Ответ

0 голосов
/ 28 сентября 2018

Предполагается, что это будет @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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...