【发布时间】:2016-11-23 01:22:42
【问题描述】:
我有一个父子组件。父组件具有index,并将其作为@Input 传递给子组件。这个index 值在父组件中不断变化,在我的子组件中,我想在每次父组件更改index 时运行一个函数。这有一个不断改变它的幻灯片组件。我怎样才能做到这一点?我已尝试使用以下代码 (this.index.subscribe(() =>),但每次尝试初始化订阅时,它都不是一个函数。
编辑:Child 模板中没有可能影响此的相关代码,因此未提供。 ngOnChange 似乎不起作用,因为指令中发生了更改,而不是 parent 的模板。
孩子:
import {Component, OnInit, ViewChild, Input} from '@angular/core';
import {Observable} from 'rxjs/Observable';
@Component({
selector: "child",
templateUrl: "components/child/child.html",
})
export class ChildComponent implements OnInit {
@Input() index: string;
currentIndex: any;
constructor() {}
ngOnInit() {}
ngOnChanges(){}
ngAfterViewInit() {
console.log("index " + this.index);
this.currentIndex = this.index.subscribe(() => {
console.log("index " + this.index);
})
}
ngOnDestroy() {
this.currentIndex.unsubscribe();
}
}
家长:
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {Page} from "ui/page";
import {ChildComponent} from '/components/child/child.component'
@Component({
selector: "parent",
template: "<child [index]="index"></child>",
directives: [ChildComponent]
})
export class ParentComponent implements OnInit {
index: string = "0,1";
constructor(private page: Page) {
}
}
【问题讨论】:
-
首先,
ParentComponent的模板应该是template,而不是templateUrl。另外,你能把ChildComponent的模板展示一下吗? -
indexinParentComponent是string并且ChildComponent期望它是Observable<any>。你就是这样使用它们的吗? -
是的,否则你会得到
Error: this.index.subscribe is not a function。 -
请提供您的
template的代码 -
this.slides来自哪里?从您的代码中,它不能是undefined以外的任何东西(它没有在任何地方设置),这会在let SlidesXml = this.slides.nativeElement;处引发错误。
标签: angular