When considering the differences between @Input
/@Output
in parent and child components versus using services that are instantiated only once with dependency injection (@Injectable()
), I find myself questioning whether there are any distinctions beyond the fact that Input/Output can only be utilized in parent and child components.
For a clearer visualization, let's look at an example:
Using @Input:
<parent-comp>
<child-comp [inputFromParent]="valueFromParent"></child-comp>
</parent-comp>
ChildComponent:
@Component({
selector: 'child-comp',
template: ...
})
export class ChildComponent {
@Input() public inputFromParent: string;
}
Using 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 component and retrieve it in the child component using dependency injection.
ChildComponent:@Component({
selector: 'child-comp',
template: ...
})
export class ChildComponent {
private value: string;
constructor(private service: Service) {
this.value = this.service.getValue;
}
}
While the first approach may seem simpler, I've noticed that managing 3-4 properties passing through parent and child components with @Input/@Output can make the template appear cluttered and confusing.