lundi 25 juin 2018

Angular - @Input and @Output vs. Injectable Service

I'm asking myself where are the differences between @Input/@Output in parent-/childcomponents and using services which is only once instatiated with dependency Injection@Injectable(). Or are there any differences besides Input/Output can only be used in parent-/child-comp.

Following Example for better visualization:

With @Input:

<parent-comp>
   <child-comp [inputFromParent]="valueFromParent"></child-comp>
</parent-comp>

ChildComponent:

@Component({
  selector: 'child-comp',
  template: ...
})
export class ChildComponent {
  @Input() public inputFromParent: string;
}

With dependency Injection

@Injectable()
export class Service {
   private value: string;

public get value(): string {
   return value;
}

public set value(input): void {
   value = input;
}

}

Now we can set the value in the parent comp. and get the value in the child comp with dependancy injection. ChildComponent:

@Component({
  selector: 'child-comp',
  template: ...
})
export class ChildComponent {
  private value: string;
  constructor(private service: Service) {
  this.value = this.service.getValue;
}

}

Even though the first approach looks simpler, I recognized using 3-4 properties carriyng through parent-/child comp. with @Input/@Output makes the tamplete very confusing and clunky.

Aucun commentaire:

Enregistrer un commentaire