Refactoring Angular components from many inputs/outputs to a single config object

前端 未结 5 1263
北海茫月
北海茫月 2021-01-03 19:56

My components often start out by having multiple @Input and @Output properties. As I add properties, it seems cleaner to switch to a single config

5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 20:44

    If you want to bundle input parameters as an object, i'd suggest to do it like this:

    export class UsingConfig implements OnInit {
        @Input() config: any;
        @Output() configChange = new EventEmitter();
    
    
        ngOnInit() {
            // Simulate something that changes prop1
            setTimeout(() => 
              this.configChange.emit({
                  ...this.config, 
                  prop1: this.config.prop1 + 1
              });
            );
        }
    }
    
    • You are creating a new config object when changing a property.
    • You are using an Output-Event to emit the changed config object.

    Both points ensure that ChangeDetection will work properly (assuming you use the more efficient OnPush strategy). Plus it's easier to follow the logic in case of debugging.

    Edit: Here's the obvious part within the parent component.

    Template:

    
    

    Code:

    export class AppComponent {
        config = {prop1: 1};
    
        onConfigChange(newConfig: any){
          // if for some reason you need to handle specific changes 
          // you could check for those here, e.g.:
          // if (this.config.prop1 !== newConfig.prop1){...
    
          this.config = newConfig;
        }
      }
    

提交回复
热议问题