Input and output events

I am looking for an argument about why use @Outputfor events is better than passing a function @Inputin Angular 2+.

Usage @Input:

Parent template:

<my-component [customEventFunction]=myFunction></my-component>

Inside parent-component.ts:

myFunction = () => {
  console.log("Hello world")
}

Inside my-component.ts

@Input() customEventFunction: Function;

someFunctionThatTriggersTheEvent() {
  this.customEventFunction();
}

Usage @Output:

Parent template:

<my-component (onCustomEvent)=myFunction()></my-component>

Inside parent-component.ts:

myFunction() {
  console.log("Hello world")
}

Inside my-component.ts

@Output() onCustomEvent: EventEmitter<any> = new EventEmitter<any>();

someFunctionThatTriggersTheEvent() {
  this.onCustomEvent.emit();
}

Both achieve the same goal, but I think the method is @Outputmore typical of what I saw in other Angular packages. It can be argued that with Input you can check if a function exists if the event should be fired only conditionally.

Thoughts?

+4
source share
3 answers

Benefits of @Output event binding:

  • @Output , , , Angular.
  • @Ouptut. , @Input, , ; . DOM, @Input onmousemove="doSomething()", @Output btn.addEventListener("mousemove", ...).
+3

no differences,

(i) @input, @input - , p >

(ii) @ConnorsFan, , @Ouput , Output, @input.

+2

@ Sajeetharan : : . :

@Component({
  selector: 'app-example',
  template: `<button (click)="runFn()">Click Me</button>`,
})
export class ExampleComponent {
  @Input() public fn: any;

  public runFn(): void {
    this.fn();
  }
}

@Component({
  selector: 'app',
  template: `<app-example [fn]="myFn"></app-example>`,
})
export class AppComponent {
  public state = 42;

  // Using arrow syntax actually *will* alert "42" because
  // arrow functions do not have their own "this" context.
  //
  // public myFn = () => window.alert(this.state);

  public myFn(): void {
    // Oops, this will alert "undefined" because this function
    // is actually executed in the scope of the child component!
    window.alert(this.state);
  }
}

@Input() . , .

Of course, there are scenarios where perhaps you don't need context. For example, perhaps you have a searchable list component that allows you to create complex data as elements and must pass a function fnEqualsso that the search can determine if the search input text matches the search element. However, these cases are usually better handled by more complex mechanisms (content projection, etc.), which increases reuse.

+2
source

Source: https://habr.com/ru/post/1691051/


All Articles