我有一个父子组件.父组件具有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();
}
}
Run Code Online (Sandbox Code Playgroud)
家长:
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) {
}
}
Run Code Online (Sandbox Code Playgroud)
Der*_*ite 45
https://angular.io/docs/ts/latest/api/core/index/Input-var.html
报价:
Angular在更改检测期间自动更新数据绑定属性.
如果您需要对输入进行一些处理,请查看get和set. https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-setter
从文档中,这是一个例子.
import { Component, Input } from '@angular/core';
@Component({
selector: 'name-child',
template: `
<h3>"{{name}}"</h3>
`
})
export class NameChildComponent {
_name: string = '<no name set>';
@Input()
set name(name: string) {
this._name = (name && name.trim()) || '<no name set>';
}
get name() { return this._name; }
}
Run Code Online (Sandbox Code Playgroud)
您不需要使用可观察对象.
Ale*_*ges 18
如其他答案中所述,您可以使用ngOnChanges生命钩子.来自Angular的文档:
ngOnChanges:在Angular设置数据绑定输入属性后响应.该方法接收当前值和先前值的更改对象.
请查看以下示例,了解如何使用它:
import { Component, Input, OnChanges } from '@angular/core';
@Component({
selector: 'child',
template: `
Value:
<span>{{ value }}</span>
<br />
<br />
Number of changes: {{ numberOfChanges }}
`
})
export class ChildComponent implements OnChanges {
@Input() value: any;
private numberOfChanges: number = 0;
ngOnChanges() {
this.numberOfChanges++;
}
}
Run Code Online (Sandbox Code Playgroud)
Plunker:http://plnkr.co/edit/XjD1jjCnqiFdbhpTibIe
And*_*ich 11
ngOnChange每次输入参数更改时调用.您甚至在Child组件中拥有它,但它没有正确实现:
ngOnChanges(changes: {[propertyName: string]: SimpleChange}) {
// check the object "changes" for new data
}
Run Code Online (Sandbox Code Playgroud)
更多细节:https://angular.io/docs/ts/latest/guide/lifecycle-hooks.html#!#onchanges
更新:index在父组件中是一个string.由于某种原因,它成为Observable了儿童组成部分.
| 归档时间: |
|
| 查看次数: |
46328 次 |
| 最近记录: |