Answer the question
In order to leave comments, you need to log in
Is passing a parent component to a child a valid coding style in Angular?
Good afternoon!
Dealing with someone else's code in Angular 7. Trying to make a list of what should be included in the refactoring.
But although I have quite a lot of programming experience, I started working with Angular quite recently, so I'm asking for advice.
There is a parent component DataInputFormComponent in it is called
<app-safety *ngFor="let safetySection of somthing; index as i" [incident]="Levels"
[viewType]="viewType" [index]="i" [componentCount]="something.length" [selectedIncidentLevel]=""></app-safety>
constructor(dataInputForm: DataInputFormComponent) {
this.dataInputForm = dataInputForm;
}
addSafetySection() {
this.dataInputForm.addSafetySection();
}
removeSafetySection(i: number) {
console.log('removing safety section with index- ', i);
this.dataInputForm.removeSafetySection(i);
}
@Output
of events (there are none in the safety component at all), but thanks to a link to the parent component. Answer the question
In order to leave comments, you need to log in
In the descendant, you do not need to inject the parent, they don’t do that.
If you really need to pass an event in this way, then they inject a service, either a root common one (like store), or a parent service.
In complex cases, you can implement the DCI pattern through a service that will know about component instances, but I would avoid it, it's hard to write cleanly.
And specifically this example, it is definitely an event through Output, it is the simplest.
I don’t know what to be proud of here :) It’s worse just to inject the component as a public one and use its methods in the template.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question