Несколько ссылок на шаблоны не работают с использованием @ ViewChild в Angular 8 - PullRequest
0 голосов
/ 29 февраля 2020

В моем родительском компоненте у меня есть несколько дочерних компонентов. Теперь я хочу получить доступ к одной общей функции из всех дочерних компонентов. Я делаю это с помощью декоратора ViewChild. Однако я получаю возвращаемое значение от 1-го дочернего компонента в ViewAfterInit (). Но когда я пытаюсь получить доступ ко второму дочернему компоненту, я получаю неопределенное значение.

Код моего файла родительского компонента .ts

import { Component, OnInit, Input, ViewEncapsulation, ViewChild, AfterViewInit} from '@angular/core';
import { NagivationComponent } from '../nagivation/nagivation.component';
import { CensusComponent } from '../your-data/census/census.component';
import { ApplicationComponent } from '../your-data/application/application.component';
import { ExistingPendingCoverageComponent } from '../your-data/existing-pending-coverage/existing-pending-coverage.component';

@Component({
  selector: 'app-your-data',
  templateUrl: './your-data.component.html',
  styleUrls: ['./your-data.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class YourDataComponent implements AfterViewInit{
  @Input() step;

  count:string = 'count1';
  constructor() {

  }
  @ViewChild(CensusComponent, {static: false}) census: CensusComponent;
  @ViewChild(ApplicationComponent, {static: false}) application: ApplicationComponent;
  ngAfterViewInit() {
  console.log('ApplicationComponent:'+ this.application)
    if(this.count === 'count1'){
       this.count = this.census.getSection(); 
    }
    if(this.count === 'count2'){
       this.count = this.application.getSection(); 
    }
  }

}

Код файла шаблона родительского компонента

<div class='container'>
  <div class='row'>
    <div class='setup-content'>
      <h1>Confirm Data/Answer Questions</h1>
      <p>Please answer all questions below. If you have questions about the data provided on this screen, please contact << Broker >> at << Phone >> or << Email >>.</p>
      <div [ngSwitch]=count>
        <app-census *ngSwitchCase="'count1'"></app-census>
        <app-application *ngSwitchCase="'count2'"></app-application>
        <app-existing-pending-coverage *ngSwitchCase="'count3'"></app-existing-pending-coverage>
      </div>
    </div>
  </div>
</div>

enter image description here

Вот ссылка ДЕМО для стекаблика https://stackblitz.com/edit/new-project-zag9um?embed=1&file=app / app.component. html У меня вопрос, почему я получаю ' неопределенный

1 Ответ

0 голосов
/ 29 февраля 2020

Для отображения следующего компонента после нажатия на кнопку. Вам необходимо использовать EventEmitter.

EventEmitter - это путь к дочернему компоненту, который может взаимодействовать с его родительским компонентом.

Angular Документы отправителя событий

Ниже объясняется, как использовать EventEmitter в этом случае.

Мое решение доступно здесь: Решение по Stackblitz

census.component.ts

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-census',
  templateUrl: './census.component.html',

})
export class CensusComponent  {
  @Output() next: EventEmitter<string> = new EventEmitter();

  getSection(){
    // after clicking on getSection we need to emit the value
    // that the parent componente will receive
    this.next.emit('count2'); // <- emit count2
  }

}

your-data.component.html

<div class='container'>
  <div class='row'>
    <div class='setup-content'>
      <h1>Confirm Data/Answer Questions</h1>
      <p>Please answer all questions below. If you have questions about the data provided on this screen, please contact << Broker >> at << Phone >> or << Email >>.</p>
      <div [ngSwitch]=count>
        <!-- here app-census pass the value to the parent component
          through onNext method ($event is the string value emitted 
          before)
        -->
        <app-census
          (next)="onNext($event)" *ngSwitchCase="'count1'"></app-census>
        <app-application *ngSwitchCase="'count2'"></app-application>        
      </div>
    </div>
  </div>
</div>

your-data.component.ts

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

@Component({
  selector: 'app-your-data',
  templateUrl: './your-data.component.html'

})
export class YourDataComponent {


  count: string = 'count1';

  onNext(count: string) {
    // parent component receives the value emitted by
    // census component and it stores the value in
    // this.count
    this.count = count;
    // now this.count is count2 and application component will be shown
  }

}

...