Angular 2/TypeScript: @Input/@output or input/output?

前端 未结 2 371
栀梦
栀梦 2020-12-10 06:04

While doing a course on Udemy we have been allowing components to be passed data dy using the @Input() decorator in the component class.

While reading t

2条回答
  •  遥遥无期
    2020-12-10 06:30

    One of the cool thing that I know you can do with decorators but I'm not if it's possible with the other way, is aliasing the variable:

    export class MyComponent {
    
     @Output('select') $onSelect = new EventEmitter(); // this is aliased
    
     @Output() finish  = new EventEmitter(); // not aliased
    
     sendUp(){
        this.$onSelect.emit('selected'); 
    
        this.finish.emit('done');
     }
    }
    

    and then from outside :

     
    

    The other one is setting a default value, you can set default value in both ways but decorators seem more convenient and less code.

    @Component({ 
      selector:'my-component'
    })
    export class MyComponent {
      @Input() id = 'default-id';     
    
      ngOnInit(){
    
        console.log('id is : ',this.id); // will output default-id if you don't pass anything when using the component
      }
    }
    

    So in this case , if the consumer doesn't pass the id as an input, you still have default-id ;

     ;
    

    Where as , if you wanted to do this with inputs array , you'd do :

    @Component({ 
      selector:'my-component',
      inputs:['id']
    })
    export class MyComponent {
      private id = 'default-id';     
    
      ngOnInit(){
    
        console.log('id is : ',this.id); // will output default-id if you don't pass anything when using the component
      }
    }
    

    The result is the same , but if you notice , in this case you have to put id both in inputs array and define it inside the class.

    EDIT:

    Apparently aliasing with outputs[] is also possible, like bellow :

    @Component({
      selector: 'my-component',
      template: `
       
      `,
      outputs: ['$onSelect: select']
    })
    export class ChildComponent {
      $onSelect = new EventEmitter(); // this is aliased
    
      sendUp() {
        this.$onSelect.emit('selected');
      }
    }
    

    But again you have to define it in two places , on in the array and one in the class , so I'd still prefer the decorators.

提交回复
热议问题