[多个模板引用在Angular 8中无法使用@ ViewChild使用

问题描述 投票:1回答:1

在我的父组件中,我有多个子组件。现在,我想从所有子组件访问一个通用功能。我通过使用ViewChild装饰器来做到这一点。但是我从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

angular angular-components viewchild
1个回答
0
投票

您正在使用ViewChild指令和ngSwitch指令操纵DOM,并破坏了Angular Change Detection的工作方式。

为了解决您的问题,您需要向Angular说您要做什么,基本上,您需要在检测到更改时对Angular说,为此,您可以在每次需要时注入ChangeDetectorRef并应用detectChanges方法。

我不知道这样做的意义,但是我留下了一个示例。

Example on Stackblitz

这里有关于您正在做的事情以及“角度检测更改”如何工作的说明。

Explanation here

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

  constructor(private cd: ChangeDetectorRef) {}

  ngAfterViewInit() {
    if(this.count === 'count1'){
      this.count = this.census.getSection();
      this.cd.detectChanges();
    }
    if(this.count === 'count2'){
      this.count = this.application.getSection();
      this.cd.detectChanges();
    }
  }
© www.soinside.com 2019 - 2024. All rights reserved.