angular - 如何使用具有默认值的输入变量的设置方法?
问题描述
在一个组件中,我有两个输入变量
@Input() public data: User[] = []
@Input() public type: UserType = 'A1';
如果上述变量的值发生变化,我需要为此调用一个函数,我使用了下面的方法
ngOnChanges(changes: SimpleChanges) {
if (changes.type && changes.data) {
this.userList = this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
}
}
但我需要改变这一点,我需要使用 Setters 函数而不是 ngOnChanges。以下是我的方法,但我遇到了错误。我已经评论了直接声明
//@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这样的变量类型我收到错误
@Input() set public type(value: UserType) {
}
2) 无法设置默认值
3) 困惑如何调用 getAllUsersList
解决方案
private type: UserType = 'A1';
@Input('type') set setType(type: UserType) {
this.type = type;
this.userList();
}
private data: User[] = [];
@Input('data') set setData(data: User[] ) {
this.data = data;
this.userList();
}
private userList() {
if (this.data && this.user.length) {
this.userService.getAllUsersList(changes.type.currentValue, changes.data.currentValue);
}
}
ngAfterViewInit() {
// If there is no input value, then setter is never called.
// So we have to call it.
this.userList();
}
推荐阅读
- javascript - (Angular) 如何将 html 中的#tag 定义转换为 Javascript?
- php - 如何在 PHP-OpenCloud/OpenStack 中批量删除
- excel - VBA 是否无法将整个段落替换为 Word 文档?
- powerapps - 循环遍历 Excel 数据源行
- angular - 在延迟加载的模块之间共享的 Angular 6 服务中注入 URL
- sql - Liquibase:列缓存
- c - 如何获取文件描述符的模式?
- java - 获取 Maven 编译错误无法执行目标 org.apache.maven.plugins
- python - 带有注意类的 Keras LSTM 输入维度设置
- ibm-cloud - 无法在管道作业中部署附加包