A
A
andreys752019-09-02 11:37:24
Angular
andreys75, 2019-09-02 11:37:24

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>

The fact that it is necessary to transfer the formation of a list of strings already in the component itself, I understand, but I'm interested in how the data is returned from the component.
The SafetyComponent constructor has the following code:
constructor(dataInputForm: DataInputFormComponent) {
        this.dataInputForm = dataInputForm;
  }

Those. we get a link to the parent component, and when in this component we click the button to add another record, in the event handler we call the function for adding from the parent component
addSafetySection() {
    this.dataInputForm.addSafetySection();
  }

  removeSafetySection(i: number) {
    console.log('removing safety section with index- ', i);
    this.dataInputForm.removeSafetySection(i);
  }

Thus, the component is not actually isolated from the parent component, it passes data up the tree not with the help @Outputof events (there are none in the safety component at all), but thanks to a link to the parent component.
In my opinion, this is terrible, but maybe I don’t understand something, people here are proud of this decision, and since I’m new to the company, I will be grateful for feedback on whether such code needs to be refactored or is this acceptable practice in Angular

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-09-02
@Xuxicheta

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 question

Ask a Question

731 491 924 answers to any question