Я пытаюсь выучить Angular 2.
Я хотел бы получить доступ к дочернему компоненту из родительского компонента, используя аннотацию @ViewChild.
Вот несколько строк кода:
В 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- tile (действительно, я вижу заголовок).
Примечание: класс BodyContent внедряется внутри другого шаблона (Body) с использованием DynamicComponetLoader: 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
и, конечно, получаю исключение, когда пытаюсь вставить что-то в массив "tile": "нет плиток свойства для" undefined "".
Еще одна вещь: компонент FilterTiles, кажется, правильно загружен, так как я могу видеть HTML-шаблон для него.
Любое предложение? Спасибо
У меня была похожая проблема, и я решил опубликовать ее на тот случай, если кто-то еще совершит ту же ошибку. Во-первых, необходимо учитывать AfterViewInit
; вам нужно дождаться инициализации представления, прежде чем вы сможете получить доступ к своему @ViewChild
. Тем не менее, мой @ViewChild
все еще возвращал @ViewChild
. Проблема была в моем *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, вызывающий представление undefined. Ответ заключается в использовании 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. Надеюсь, это поможет.
this.SearchGrid
вы должны использовать синтаксис, например, setTimeout(()=>{ ///your code here }, 1);
чтобы избежать исключения: выражение было изменено после его проверки
Вы можете использовать сеттер для @ViewChild()
@ViewChild(FilterTiles) set ft(tiles: FilterTiles) {
console.log(tiles);
};
Если у вас есть оболочка ngIf, сеттер будет вызываться с неопределенным значением, а затем снова со ссылкой, как только ngIf разрешит его рендеринг.
Моя проблема была чем-то еще, хотя. Я не включил модуль, содержащий мои "FilterTiles" в мои app.modules. Шаблон не выдавал ошибку, но ссылка всегда была неопределенной.
Это сработало для меня.
Мой компонент с именем 'my-component', например, был отображен с помощью * ngIf = "showMe" так:
<my-component [showMe]="showMe" *ngIf="showMe"></my-component>
Итак, когда компонент инициализирован, компонент еще не отображается до тех пор, пока "showMe" не будет истинным. Таким образом, мои ссылки @ViewChild были undefined.
Здесь я использовал @ViewChildren и QueryList, которые он возвращает. См. angular статью о QueryList и демонстрации использования @ViewChildren.
Вы можете использовать QueryList, который @ViewChildren возвращает и подписывается на любые изменения ссылочных элементов, используя rxjs, как показано ниже. @ViewChid не обладает этой способностью.
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
Надеюсь, это поможет кому-то сэкономить время и разочарование.
.take(1).subscribe()
, но отличный ответ, большое спасибо!
Моим обходным путем было использовать [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";
}
}
....
Моим решением было заменить * ngIf на [hidden]. Недостатком было то, что все дочерние компоненты присутствовали в коде DOM. Но работал для моих требований.
Это работает для меня, см. пример ниже.
import {Component, ViewChild, ElementRef} from 'angular2/core';
@Component({
selector: 'app',
template: `
<a (click)="toggle($event)">Toggle</a>
<div *ngIf="visible">
<input #control name="value" [(ngModel)]="value" type="text" />
</div>
`,
})
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(); });
}
}
}
Он должен работать.
Но как Гюнтер Цохбауэр сказал, что в шаблоне должна быть какая-то другая проблема. Я создал kinda Relevant-Plunkr-Answer. Просьба проверить панель браузера.
boot.ts
@Component({
selector: 'my-app'
, template: `<div> <h1> BodyContent </h1></div>
<filter></filter>
<button (click)="onClickSidebar()">Click Me</button>
`
, 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: '<div> <h4>Filter tiles </h4></div>'
})
export class FilterTiles {
public tiles = [];
public constructor(){};
}
Это работает как шарм. Пожалуйста, дважды проверьте свои теги и ссылки.
Спасибо...
Я исправляю это, просто добавив SetTimeout после установки видимого компонента
Мой HTML:
<input #txtBus *ngIf[show]>
Мой компонент 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);
}
}
Моим решением было переместить ngIf извне дочернего компонента внутрь дочернего компонента в div, который завернул весь раздел html. Таким образом, он все еще скрывался, когда это было необходимо, но смог загрузить компонент, и я мог бы ссылаться на него в родительском.
В моем случае у меня был установщик входной переменной, использующий ViewChild, и ViewChild находился внутри директивы * ngIf, так что сеттер пытался получить к ней доступ до отображения * ngIf (он бы работал нормально без * ngIf, но будет не работает, если он всегда был установлен в true с * ngIf = "true").
Чтобы решить эту проблему, я использовал Rxjs, чтобы убедиться, что любая ссылка на ViewChild ждала, пока представление не будет инициировано. Сначала создайте тему, которая завершается, когда после просмотра 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;
В моем случае я знал, что дочерний компонент всегда будет присутствовать, но хотел изменить состояние до инициализации дочернего элемента, чтобы сохранить работу.
Я выбираю тестирование на ребенка, пока он не появится, и сразу же внесу изменения, что спасло меня от цикла изменений дочернего компонента.
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
. setTimeout
эффективно сбрасывает функцию в конец списка ожидающих операций.
У меня была аналогичная проблема, где ViewChild
находился внутри предложения switch
, которое не загружало элемент viewChild до того, как он ссылался. Я решил это полу-взломанным способом, но обернул ссылку ViewChild
в setTimeout
, которая была выполнена немедленно (т.е. 0 мс)
Решение, которое работало для меня, состояло в том, чтобы добавить директиву в объявлениях в app.module.ts
Некий общий подход:
Вы можете создать метод, который будет ждать, пока ViewChild
будет готов
function waitWhileViewChildIsReady(parent: any, viewChildName: string, refreshRateSec: number = 50, maxWaitTime: number = 3000): Observable<any> {
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<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
Использование:
// Now you can do it in any place of your code
waitWhileViewChildIsReady(this, 'yourViewChildName').subscribe(() =>{
// your logic here
})
Это будет легко. Попробуйте это, если вы вообще не хотите визуализировать элемент и все равно проходите без ошибок. Просто поставьте условие if для проверки на undefined.:
@ViewChild(ControlsComponent) controls:ControlsComponent;
.....
if(controls){
controls.yourChildFunction();
}