首页 > 解决方案 > 如何使用具有默认值的输入变量的设置方法?

问题描述

在一个组件中,我有两个输入变量

@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

标签: angular

解决方案


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();
}

推荐阅读