我正在学习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模板。

有什么建议吗?


当前回答

对我来说,问题是我引用了元素上的ID。

@ViewChild('survey-form') slides:IonSlides;

<div id="survey-form"></div>

而不是这样:

@ViewChild('surveyForm') slides:IonSlides;

<div #surveyForm></div>

其他回答

这对我很管用。

例如,我的名为' 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导致视图未定义。答案是使用ViewChildren而不是ViewChild。我有类似的问题,我不想要一个网格显示,直到所有的参考数据已经加载。

html:

   <section class="well" *ngIf="LookupData != null">
       <h4 class="ra-well-title">Results</h4>
       <kendo-grid #searchGrid> </kendo-grid>
   </section>

组件代码

import { Component, ViewChildren, OnInit, AfterViewInit, QueryList  } from '@angular/core';
import { GridComponent } from '@progress/kendo-angular-grid';

export class SearchComponent implements OnInit, AfterViewInit
{
    //other code emitted for clarity

    @ViewChildren("searchGrid")
    public Grids: QueryList<GridComponent>

    private SearchGrid: GridComponent

    public ngAfterViewInit(): void
    {
        
        this.Grids.changes.subscribe((comps: QueryList <GridComponent>) =>
        {
            this.SearchGrid = comps.first;
        });

       
    }
}

这里我们使用了ViewChildren,你可以在它上面监听变化。在本例中,任何引用#searchGrid的子元素。

对我来说,使用ngAfterViewInit而不是ngOnInit修复了这个问题:

export class AppComponent implements OnInit {
  @ViewChild('video') video;
  ngOnInit(){
    // <-- in here video is undefined
  }
  public ngAfterViewInit()
  {
    console.log(this.video.nativeElement) // <-- you can access it here
  }
}

我也遇到过类似的问题,我想我应该发布这篇文章,以防别人犯同样的错误。首先,要考虑的一件事是AfterViewInit;你需要等待视图被初始化,然后才能访问@ViewChild。但是,我的@ViewChild仍然返回null。问题出在我的*ngIf。*ngIf指令杀死了我的控件组件,所以我不能引用它。

import { Component, ViewChild, OnInit, AfterViewInit } from 'angular2/core';
import { ControlsComponent } from './controls/controls.component';
import { SlideshowComponent } from './slideshow/slideshow.component';

@Component({
  selector: 'app',
  template: `
    <controls *ngIf="controlsOn"></controls>
    <slideshow (mousemove)="onMouseMove()"></slideshow>
  `,
  directives: [SlideshowComponent, ControlsComponent],
})
export class AppComponent {
  @ViewChild(ControlsComponent) controls: ControlsComponent;

  controlsOn: boolean = false;

  ngOnInit() {
    console.log('on init', this.controls);
    // this returns undefined
  }

  ngAfterViewInit() {
    console.log('on after view init', this.controls);
    // this returns null
  }

  onMouseMove(event) {
    this.controls.show();
    // throws an error because controls is null
  }
}

编辑 正如下面@Ashg提到的,一个解决方案是使用@ViewChildren而不是@ViewChild。

使用[hidden]代替*ngif,因为*ngif在条件不满足时终止代码。

<div [hidden]="YourVariable">
   Show Something
</div>