[typescript] 각도 2 @ViewChild 주석은 정의되지 않은 값을 반환

Angular 2를 배우려고합니다.

@ViewChild Annotation을 사용하여 부모 구성 요소에서 자식 구성 요소에 액세스하고 싶습니다 .

다음은 몇 줄의 코드입니다.

에서 BodyContent.ts 내가 가진 :

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를 사용하여 다른 템플릿 (Body) 내에 주입됩니다. dcl.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콘솔 로그에, 내가 얻을 undefined, 나는이 “타일”배열 안에 무언가를 추진하려고 할 때, 물론 나는 예외를 얻을 : ‘ “정의되지 않은”에 대한 속성 타일’ .

한 가지 더 : FilterTiles 구성 요소가 html 템플릿을 볼 수 있으므로 올바르게로드 된 것 같습니다.

어떠한 제안? 감사



답변

비슷한 문제가 있었고 다른 사람이 같은 실수를 한 경우 게시 할 것이라고 생각했습니다. 우선 고려해야 할 한 가지입니다 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


답변

앞에서 언급 한 문제 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있습니다. 도움이 되었기를 바랍니다.


답변

세터를 사용할 수 있습니다. @ViewChild()

@ViewChild(FilterTiles) set ft(tiles: FilterTiles) {
    console.log(tiles);
};

ngIf 래퍼가 있으면 setter가 정의되지 않은 상태로 호출 된 다음 ngIf가 렌더링을 허용하면 한 번 참조로 다시 호출됩니다.

내 문제는 다른 것이 었습니다. app.modules에 “FilterTiles”가 포함 된 모듈을 포함시키지 않았습니다. 템플릿에서 오류가 발생하지 않았지만 참조는 항상 정의되지 않았습니다.


답변

이것은 나를 위해 일했습니다.

예를 들어, ‘my-component’라는 내 구성 요소는 다음과 같이 * ngIf = “showMe”를 사용하여 표시되었습니다.

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

따라서 구성 요소가 초기화되면 “showMe”가 true가 될 때까지 구성 요소가 아직 표시되지 않습니다. 따라서 내 @ViewChild 참조는 모두 정의되지 않았습니다.

이것은 @ViewChildren과 그것이 반환하는 QueryList를 사용한 곳입니다. QueryList 및 @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

누군가가 시간과 좌절을 덜어 줄 수 있기를 바랍니다.


답변

내 해결 방법은 [style.display]="getControlsOnStyleDisplay()"대신 사용하는 것이 었습니다 *ngIf="controlsOn". 블록이 있지만 표시되지 않습니다.

@Component({
selector: 'app',
template:  `
    <controls [style.display]="getControlsOnStyleDisplay()"></controls>
...

export class AppComponent {
  @ViewChild(ControlsComponent) controls:ControlsComponent;

  controlsOn:boolean = false;

  getControlsOnStyleDisplay() {
    if(this.controlsOn) {
      return "block";
    } else {
      return "none";
    }
  }
....


답변

내 문제를 해결 한 것은 static로 설정되어 false있었습니다.

@ViewChild(ClrForm, {static: false}) clrForm;

static꺼져의 @ViewChild때 참조 각도에 의해 업데이트되는 *ngIf지침이 변경됩니다.


답변

이것에 대한 나의 해결책은로 대체 *ngIf 하는 것이 었 습니다 [hidden]. 단점은 모든 하위 구성 요소가 코드 DOM에 존재한다는 것입니다. 그러나 내 요구 사항을 위해 일했습니다.