如何将 set 方法与具有默认值的 Input vatiables 一起使用? [英] How to use set methods with Input vatiables having defaults value as well?
本文介绍了如何将 set 方法与具有默认值的 Input vatiables 一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在一个组件中,我有两个输入变量
In a component I have two input variables
@Input() public data: User[] = []
@Input() public type: UserType = 'A1';
如果上述变量的值发生变化,我需要为此调用一个函数,我使用了下面的方法
If the value of above variables change I need to call a function for this I have used below method
ngOnChanges(changes: SimpleChanges) {
if (changes.type && changes.data) {
this.userList = this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
}
}
但我需要改变这个我需要使用 Setters 函数而不是 ngOnChanges.以下是我的方法,但出现错误.我已评论直接声明
But I need to change this I need to use Setters function instead of ngOnChanges. Below is my approaches but I am getting error. I have commented direct declaration
//@Input() public data: User[] = [] not using this type declaration
// @Input() public type: UserType = 'A1'; not using this type declaration
@Input() set type(value: UserType) {
}
@Input() set data(value: User[] ) {
}
我遇到的问题
1) 执行此操作时无法像 public 一样定义变量类型,我收到错误
1) Not able to define variable type like public when I am doing this I am getting error
@Input() set public type(value: UserType) {
}
2) 无法设置默认值
3) 困惑如何调用 getAllUsersList
3) Confused how to call getAllUsersList
推荐答案
从 npm 安装 property-watch-decorator
.
npm i property-watch-decorator
然后在 @input
export class TestComponent {
@OnChange(TestComponent.prototype.userList)
@Input() type: UserType = 'A1'
@OnChange(TestComponent.prototype.userList)
@Input data: User[] = [];
private userList() {
if (this.data && this.user.length) {
this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
}
}
ngAfterViewInit() {
// To handle default values.
this.userList();
}
}
这篇关于如何将 set 方法与具有默认值的 Input vatiables 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文