A
A
andreys752019-09-03 14:39:38
Angular
andreys75, 2019-09-03 14:39:38

Why is @Output and emit events not required if an array was passed to @Input?

Hi all!
The code works, but I don’t understand why, according to all the docks and courses, it seems like it shouldn’t work.
There is a parent component - the big form. The parent component implements work with services: loading, updating and deleting data.
Since the form is very large, we break it into independent components. here is one child:

<app-safety
            [(SafetyIncidents)] = "SafetyIncidents"
            [incidentLevels]="incidentLevels"
            [viewType]="viewType"
            [(IncidentsToDelete)]="safetyIncidentsToDelete"
            (ready)="ready($event,'SafetyBlock')">
 </app-safety>

SafetyIncidents is an array Array<SafetyIncident>.
. Inside the descendant component (safety) we output strings for each element. (decided not to make another component)
*ngFor="let Incident of SafetyIncidents; let index = index"

and for each form element we bind something like this:
<mat-form-field class="col-md-1">
        <input name=SafetyIncidentImpactId [(ngModel)]="Incident.ImpactId" matInput placeholder="Impact ID">
 </mat-form-field>
...
<mat-select [(value)]="Incident.IncidentLevel" [compareWith]="compareObjects">
     <mat-option>--</mat-option>
     <mat-option *ngFor="let level of incidentLevels" [value]="level">{{level.Title}}</mat-option>
</mat-select>

The submit button and the call to the function of saving data to the database are in the parent component,
I commented out the line
//@Output() SafetyIncedentsChange = new EventEmitter<SafetyIncident[]>();

And in general, I have not had time to call the child component in the code yet. SafetyIncedentsChange.emit(SafetyIncidents);
But in the parent component, all changes are there and are perfectly saved in the database.
Why does it work???
The other component I'm passing @Input to is a simple object that doesn't update without triggering an event!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Shvets, 2019-09-03
@andreys75

You pass a reference to an array and change its contents.
The object is changing. Angular just doesn't know about it.
The emitter is needed to notify the parent component that the value of the variable has changed.
If the binding is two-way, then the parent writes to its property what came in the emit.
(hidden (itemChange) = "item = $event")
If the object - the value of the property does not change, the same reference to the same object will come to $event
.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question