on
각도 2 @ViewChild 주석은 정의되지 않은 값을 반환합니다.
각도 2 @ViewChild 주석은 정의되지 않은 값을 반환합니다.
각도 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
FilterTiles.html
Tiles loaded ... stuff ...
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: ` `, 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 :
Results
구성 요소 코드
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 private SearchGrid: GridComponent public ngAfterViewInit(): void { this.Grids.changes.subscribe((comps: QueryList ) => { 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"를 사용하여 표시되었습니다.
따라서 구성 요소가 초기화되면 "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; // this reference is just pointing to a template reference variable in the component html file (i.e. ) @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: ` ... export class AppComponent { @ViewChild(ControlsComponent) controls:ControlsComponent; controlsOn:boolean = false; getControlsOnStyleDisplay() { if(this.controlsOn) { return "block"; } else { return "none"; } } ....
이것에 대한 나의 해결책은로 대체 *ngIf 하는 것이 었 습니다 [hidden] . 단점은 모든 하위 구성 요소가 코드 DOM에 존재한다는 것입니다. 그러나 내 요구 사항을 위해 일했습니다.
작동해야합니다.
그러나 Günter Zöchbauer 는 템플릿에 다른 문제가 있다고 말했다. 나는 Relevant-Plunkr-Answer를 만들었습니다 . 탄원은 브라우저의 콘솔을 확인합니다.
boot.ts
@Component({ selector: 'my-app' , template: ` BodyContent Click Me ` , directives: [FilterTiles] }) export class BodyContent { @ViewChild(FilterTiles) ft:FilterTiles; public onClickSidebar() { console.log(this.ft); this.ft.tiles.push("entered"); } }
filterTiles.ts
@Component({ selector: 'filter', template: ' Filter tiles ' }) export class FilterTiles { public tiles = []; public constructor(){}; }
그것은 매력처럼 작동합니다. 태그와 참조를 다시 확인하십시오.
감사...
내 경우, 나는를 사용하여 입력 변수 세터를했다 ViewChild , 그리고는 ViewChild 의 내부했다 *ngIf 세터가 전에 액세스를 시도 그래서, 지시문을 *ngIf 포함하지 않는 렌더링 (작동 것 잘 *ngIf 하지만 작업은 항상로 설정하지 않을 경우 )에 해당합니다 *ngIf="true" .
해결하기 위해 Rxjs를 사용 ViewChild 하여 뷰가 시작될 때까지 대기 한 참조를 확인 했습니다. 먼저 view init 후에 완료되는 주제를 작성하십시오.
export class MyComponent implements AfterViewInit { private _viewInitWaiter$ = new Subject(); ngAfterViewInit(): void { this._viewInitWaiter$.complete(); } }
그런 다음 주제가 완료된 후 람다를 가져 와서 실행하는 함수를 만듭니다.
private _executeAfterViewInit(func: () => any): any { this._viewInitWaiter$.subscribe(null, null, () => { return func(); }) }
마지막으로 ViewChild에 대한 참조가이 기능을 사용하는지 확인하십시오.
@Input() set myInput(val: any) { this._executeAfterViewInit(() => { const viewChildProperty = this.viewChild.someProperty; ... }); } @ViewChild('viewChildRefName', {read: MyViewChildComponent}) viewChild: MyViewChildComponent;
이것은 저에게 효과적입니다. 아래 예를 참조하십시오.
import {Component, ViewChild, ElementRef} from 'angular2/core'; @Component({ selector: 'app', template: ` Toggle `, }) export class AppComponent { private elementRef: ElementRef; @ViewChild('control') set controlElRef(elementRef: ElementRef) { this.elementRef = elementRef; } visible:boolean; toggle($event: Event) { this.visible = !this.visible; if(this.visible) { setTimeout(() => { this.elementRef.nativeElement.focus(); }); } } }
비슷한 문제 가있어서 참조하기 전에 viewChild 요소를로드하지 않은 절 ViewChild 내부에 switch 있었습니다. 나는 그것을 반 해키 방식으로 해결했지만 즉시 실행되는 ViewChild 참조로 래핑합니다 setTimeout (예 : 0ms)
이것에 대한 나의 해결책은 ngIf를 자식 구성 요소 외부에서 html의 전체 섹션을 감싸는 div의 자식 구성 요소 내부로 옮기는 것입니다. 그런 식으로 필요할 때 숨겨져 있었지만 구성 요소를로드 할 수 있었고 부모에서 참조 할 수있었습니다.
구성 요소를 표시 한 후 SetTimeout을 추가하여 수정합니다.
내 HTML :
내 컴포넌트 JS
@Component({ selector: "app-topbar", templateUrl: "./topbar.component.html", styleUrls: ["./topbar.component.scss"] }) export class TopbarComponent implements OnInit { public show:boolean=false; @ViewChild("txtBus") private inputBusRef: ElementRef; constructor() { } ngOnInit() {} ngOnDestroy(): void { } showInput() { this.show = true; setTimeout(()=>{ this.inputBusRef.nativeElement.focus(); },500); } }
필자의 경우 하위 구성 요소가 항상 존재한다는 것을 알았지 만 작업을 저장하기 위해 초기화하기 전에 상태를 변경하고 싶었습니다.
I choose to test for the child until it appeared and make changes immediately, which saved me a change cycle on the child component.
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)); } }
Alertnatively, you could add a max number of attempts or add a few ms delay to the setTimeout . setTimeout effectively throws the function to the bottom of the list of pending operations.
A kind of generic approach:
You can create a method that will wait until ViewChild will be ready
function waitWhileViewChildIsReady(parent: any, viewChildName: string, refreshRateSec: number = 50, maxWaitTime: number = 3000): Observable { return interval(refreshRateSec) .pipe( takeWhile(() => !isDefined(parent[viewChildName])), filter(x => x === undefined), takeUntil(timer(maxWaitTime)), endWith(parent[viewChildName]), flatMap(v => { if (!parent[viewChildName]) throw new Error(`ViewChild "${viewChildName}" is never ready`); return of(!parent[viewChildName]); }) ); } function isDefined(value: T | undefined | null): value is T { return value !== undefined && value !== null; }
Usage:
// Now you can do it in any place of your code waitWhileViewChildIsReady(this, 'yourViewChildName').subscribe(() =>{ // your logic here })
For me the problem was I was referencing the ID on the element.
@ViewChild('survey-form') slides:IonSlides;
Instead of like this:
@ViewChild('surveyForm') slides:IonSlides;
The solution which worked for me was to add the directive in declarations in app.module.ts
Here's something that worked for me.
@ViewChild('mapSearch', { read: ElementRef }) mapInput: ElementRef; ngAfterViewInit() { interval(1000).pipe( switchMap(() => of(this.mapInput)), filter(response => response instanceof ElementRef), take(1)) .subscribe((input: ElementRef) => { //do stuff }); }
So I basically set a check every second until the *ngIf becomes true and then I do my stuff related to the ElementRef .
참고URL : https://stackoverflow.com/questions/34947154/angular-2-viewchild-annotation-returns-undefined
from http://lottoking.tistory.com/874 by ccl(A) rewrite - 2020-05-12 08:27:03