在angular2中,如何为@Input发送的对象上更改的属性获取onChanges
In angular2, how to get onChanges for properties changed on an object sent in for an @Input
我有一个指令,上面有一个 @Input
接受 class。
@Directive({selector: 'my-directive'})
@View({directives: [CORE_DIRECTIVES]})
export class MyDirective {
@Input() inputSettings : SettingsClass;
@Input() count : number;
onChanges(map) {
console.log('onChanges');
}
}
指令用于html:
...
<my-directive [input-settings]="settings" [count]="settings.count"></my-directive>
...
如果 settings.count 被更改,那么 onChanges
将会触发。如果设置 class 上的任何其他 属性 发生更改,则它不会触发。
如何检测设置是否有任何 属性 更改?
Angular 只会注意到对象是否已更改为不同的对象(即对象引用已更改),因此 ngOnChanges()
不能用于解决您的问题。有关详细信息,请参阅 Victor Savkin's blog post。
您可以在 MyDirective class 中实现 ngDoCheck()
方法。 “每次检查组件或指令的输入属性时,都会调用该生命周期挂钩。使用它通过执行自定义检查来扩展更改检测。”
要实现您的自定义检查方法,您首先需要在 class SettingsClass
上实现一个 .equals()
方法,这样您就可以在 ngDoCheck()
:
ngDoCheck() {
if(!this.inputSettings.equals(this.previousInputSettings)) {
// inputSettings changed
// some logic here to react to the change
this.previousInputSettings = this.inputSettings;
}
}
另一种解决方案在您无法控制传递给组件的对象时很有用,它是使用 ViewChild 并直接调用方法来更新对象:
在子组件中添加如下函数:
public updateSettings(obj: SettingsClass) {
this.inputSettings = obj;
}
并在父组件中调用 updateSettings 函数:
@Component({
selector: 'app-mycomponnent',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class PlayComponent implements OnInit {
@ViewChild(MyDirectiveComponent,{static: false}) mydirective;
elsewhereinthecode() {
// When you need to update call :
mydirective.updateSettings(settingsObject);
}
}
我有一个指令,上面有一个 @Input
接受 class。
@Directive({selector: 'my-directive'})
@View({directives: [CORE_DIRECTIVES]})
export class MyDirective {
@Input() inputSettings : SettingsClass;
@Input() count : number;
onChanges(map) {
console.log('onChanges');
}
}
指令用于html:
...
<my-directive [input-settings]="settings" [count]="settings.count"></my-directive>
...
如果 settings.count 被更改,那么 onChanges
将会触发。如果设置 class 上的任何其他 属性 发生更改,则它不会触发。
如何检测设置是否有任何 属性 更改?
Angular 只会注意到对象是否已更改为不同的对象(即对象引用已更改),因此 ngOnChanges()
不能用于解决您的问题。有关详细信息,请参阅 Victor Savkin's blog post。
您可以在 MyDirective class 中实现 ngDoCheck()
方法。 “每次检查组件或指令的输入属性时,都会调用该生命周期挂钩。使用它通过执行自定义检查来扩展更改检测。”
要实现您的自定义检查方法,您首先需要在 class SettingsClass
上实现一个 .equals()
方法,这样您就可以在 ngDoCheck()
:
ngDoCheck() {
if(!this.inputSettings.equals(this.previousInputSettings)) {
// inputSettings changed
// some logic here to react to the change
this.previousInputSettings = this.inputSettings;
}
}
另一种解决方案在您无法控制传递给组件的对象时很有用,它是使用 ViewChild 并直接调用方法来更新对象:
在子组件中添加如下函数:
public updateSettings(obj: SettingsClass) {
this.inputSettings = obj;
}
并在父组件中调用 updateSettings 函数:
@Component({
selector: 'app-mycomponnent',
templateUrl: './my.component.html',
styleUrls: ['./my.component.css']
})
export class PlayComponent implements OnInit {
@ViewChild(MyDirectiveComponent,{static: false}) mydirective;
elsewhereinthecode() {
// When you need to update call :
mydirective.updateSettings(settingsObject);
}
}