我正在学习Angular 2。

我想使用@ViewChild Annotation从父组件访问子组件。

下面是一些代码行:

在BodyContent。我有:

import { ViewChild, Component, Injectable } from 'angular2/core';
import { FilterTiles } from '../Components/FilterTiles/FilterTiles';

@Component({
    selector: 'ico-body-content',
    templateUrl: 'App/Pages/Filters/BodyContent/BodyContent.html',
    directives: [FilterTiles] 
})
export class BodyContent {
    @ViewChild(FilterTiles) ft: FilterTiles;

    public onClickSidebar(clickedElement: string) {
        console.log(this.ft);
        var startingFilter = {
            title: 'cognomi',
            values: [ 'griffin', 'simpson' ]
        }
        this.ft.tiles.push(startingFilter);
    } 
}

FilterTiles.ts:

 import { Component } from 'angular2/core';

 @Component({
     selector: 'ico-filter-tiles',
     templateUrl: 'App/Pages/Filters/Components/FilterTiles/FilterTiles.html'
 })
 export class FilterTiles {
     public tiles = [];

     public constructor(){};
 }

最后是模板(在评论中建议):

BodyContent.html

<div (click)="onClickSidebar()" class="row" style="height:200px; background-color:red;">
    <ico-filter-tiles></ico-filter-tiles>
</div>

FilterTiles.html

<h1>Tiles loaded</h1>
<div *ngFor="#tile of tiles" class="col-md-4">
     ... stuff ...
</div>

FilterTiles.html模板被正确加载到ico-filter-tiles标签(确实我能够看到标题)。

注意:BodyContent类使用DynamicComponetLoader: dcl注入到另一个模板(Body)中。loadAsRoot(BodyContent, '#ico-bodyContent',注入器):

import { ViewChild, Component, DynamicComponentLoader, Injector } from 'angular2/core';
import { Body } from '../../Layout/Dashboard/Body/Body';
import { BodyContent } from './BodyContent/BodyContent';

@Component({
    selector: 'filters',
    templateUrl: 'App/Pages/Filters/Filters.html',
    directives: [Body, Sidebar, Navbar]
})
export class Filters {

    constructor(dcl: DynamicComponentLoader, injector: Injector) {
       dcl.loadAsRoot(BodyContent, '#ico-bodyContent', injector);
       dcl.loadAsRoot(SidebarContent, '#ico-sidebarContent', injector);
   } 
}

问题是,当我试图将ft写入控制台日志时,我得到了未定义,当然,当我试图在“tiles”数组内推一些东西时,我会得到一个异常:“没有属性瓷砖”。

还有一件事:FilterTiles组件似乎正确加载,因为我能够看到它的html模板。

有什么建议吗?


当前回答

这对我很管用。

例如,我的名为' My -component'的组件使用*ngIf="showMe"来显示 像这样:

<my-component [showMe]="showMe" *ngIf="showMe"></my-component>

因此,当组件初始化时,直到"showMe"为真,组件才会显示出来。因此,我的@ViewChild引用都没有定义。

这是我使用@ViewChildren和它返回的QueryList的地方。参见QueryList上的angular文章和@ViewChildren使用演示。

你可以使用@ViewChildren返回的QueryList,并使用rxjs订阅对引用项的任何更改,如下所示。@ViewChild没有这个能力。

import { Component, ViewChildren, ElementRef, OnChanges, QueryList, Input } from '@angular/core';
import 'rxjs/Rx';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnChanges {

  @ViewChildren('ref') ref: QueryList<any>; // this reference is just pointing to a template reference variable in the component html file (i.e. <div #ref></div> )
  @Input() showMe; // this is passed into my component from the parent as a    

  ngOnChanges () { // ngOnChanges is a component LifeCycle Hook that should run the following code when there is a change to the components view (like when the child elements appear in the DOM for example)
    if(showMe) // this if statement checks to see if the component has appeared becuase ngOnChanges may fire for other reasons
      this.ref.changes.subscribe( // subscribe to any changes to the ref which should change from undefined to an actual value once showMe is switched to true (which triggers *ngIf to show the component)
        (result) => {
          // console.log(result.first['_results'][0].nativeElement);                                         
          console.log(result.first.nativeElement);                                          

          // Do Stuff with referenced element here...   
        } 
      ); // end subscribe
    } // end if
  } // end onChanges 
} // end Class

希望这能帮助一些人节省一些时间和挫折。

其他回答

对我来说有效的解决方案是在app.module.ts的声明中添加指令

这对我很管用。

例如,我的名为' My -component'的组件使用*ngIf="showMe"来显示 像这样:

<my-component [showMe]="showMe" *ngIf="showMe"></my-component>

因此,当组件初始化时,直到"showMe"为真,组件才会显示出来。因此,我的@ViewChild引用都没有定义。

这是我使用@ViewChildren和它返回的QueryList的地方。参见QueryList上的angular文章和@ViewChildren使用演示。

你可以使用@ViewChildren返回的QueryList,并使用rxjs订阅对引用项的任何更改,如下所示。@ViewChild没有这个能力。

import { Component, ViewChildren, ElementRef, OnChanges, QueryList, Input } from '@angular/core';
import 'rxjs/Rx';

@Component({
    selector: 'my-component',
    templateUrl: './my-component.component.html',
    styleUrls: ['./my-component.component.css']
})
export class MyComponent implements OnChanges {

  @ViewChildren('ref') ref: QueryList<any>; // this reference is just pointing to a template reference variable in the component html file (i.e. <div #ref></div> )
  @Input() showMe; // this is passed into my component from the parent as a    

  ngOnChanges () { // ngOnChanges is a component LifeCycle Hook that should run the following code when there is a change to the components view (like when the child elements appear in the DOM for example)
    if(showMe) // this if statement checks to see if the component has appeared becuase ngOnChanges may fire for other reasons
      this.ref.changes.subscribe( // subscribe to any changes to the ref which should change from undefined to an actual value once showMe is switched to true (which triggers *ngIf to show the component)
        (result) => {
          // console.log(result.first['_results'][0].nativeElement);                                         
          console.log(result.first.nativeElement);                                          

          // Do Stuff with referenced element here...   
        } 
      ); // end subscribe
    } // end if
  } // end onChanges 
} // end Class

希望这能帮助一些人节省一些时间和挫折。

如果一个*ngIf="show"阻止ViewChild被渲染,并且在你的show变为true后你需要ViewChild,它帮助我在我设置show为true后立即触发ChangeDetectorRef.detectChanges()。

在此之后,*ngIf创建组件并渲染ViewChild,你可以在之后使用它。只是输入了一个快速的示例代码。

@ViewChild(MatSort) sort: MatSort;    

constructor(private cdRef: ChangeDetectorRef) {}

ngOnInit() {
  this.show = false;
  this.someObservable()
    .pipe(
      tap(() => {
        this.show = true;
        this.cdRef.detectChanges();
      })
    )
    .subscribe({
      next: (data) => {
        console.log(sort)
        this.useResult(data);
      }
    });
}

这是坏事吗?还是为什么没有人提出?

在我的例子中,我知道子组件将始终存在,但希望在初始化子组件之前更改状态以节省工作。

我选择对子组件进行测试,直到它出现并立即进行更改,这为我节省了对子组件的更改周期。

export class GroupResultsReportComponent implements OnInit {

    @ViewChild(ChildComponent) childComp: ChildComponent;

    ngOnInit(): void {
        this.WhenReady(() => this.childComp, () => { this.childComp.showBar = true; });
    }

    /**
     * Executes the work, once the test returns truthy
     * @param test a function that will return truthy once the work function is able to execute 
     * @param work a function that will execute after the test function returns truthy
     */
    private WhenReady(test: Function, work: Function) {
        if (test()) work();
        else setTimeout(this.WhenReady.bind(window, test, work));
    }
}

注意,您可以为setTimeout添加一个最大尝试次数或添加几个ms的延迟。setTimeout有效地将函数抛出到挂起操作列表的底部。

我借助更改检测以及视图容器引用的延迟初始化解决了这个问题。

HTML设置:

<ng-container *ngIf="renderMode === 'modal'" [ngTemplateOutlet]="renderModal">
</ng-container>
<ng-container *ngIf="renderMode === 'alert'" [ngTemplateOutlet]="renderAlert">
</ng-container>

<ng-template #renderModal>
  <div class="modal">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

<ng-template #renderAlert>
  <div class="alert">
    <ng-container appSelector></ng-container>
  </div>
</ng-template>

组件:

@ViewChild(SelectorDirective, { static: true }) containerSelector!: SelectorDirective;

constructor(private cdr: ChangeDetectorRef) { }

ngOnInit(): void {
  // step: 1
  this.renderMode = someService.someMethod();
  // step: 2
  this.cdr.markForCheck();
  // step: 3
  const viewContainerRef = this.containerSelector?.viewContainerRef;
  if (viewContainerRef) {
    // logic...
  }
}

修改代码,使HTML所依赖的条件(*ngIf)首先更新 一旦条件更新,手动触发ChangeDetection 在手动cdr触发后从ViewChild中获取引用,并继续进行逻辑操作。