我有一个父子组件 . 父组件具有 index
并将其作为 @Input
传递给子组件 . 这个 index
值在父组件中不断变化,在我的子组件中,我希望每次父组件更改时都运行一个函数 index
. 这有一个不断更改它的幻灯片组件 . 我怎样才能做到这一点?我尝试过使用下面的代码( this.index.subscribe(() =>
),但每次尝试初始化订阅时,我都不会使用'm getting that it' .
编辑: 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) {
}
}
3 回答
https://angular.io/docs/ts/latest/api/core/index/Input-var.html
报价:
如果您需要对输入进行一些处理,请查看get和set . https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter
从文档中,这是一个例子 .
您不需要使用可观察对象 .
如其他答案中所述,您可以使用
ngOnChanges
life hook . 来自Angular`s documentation:请查看以下示例,了解如何使用它:
Plunker:http://plnkr.co/edit/XjD1jjCnqiFdbhpTibIe
每次输入参数更改时都会调用
ngOnChange
. 您甚至可以在Child
组件中使用它,但它没有正确实现:更多细节:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges
父组件中的 Update :
index
是string
. 由于某种原因,它在子组件中变成了Observable
.