Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the data between parent to child

Tags:

angular

I am able to pass the data from parent to child on template binding(on ngInit). but how can i share the same data when its updated at parent component. Is there is observable to share(from parent to child component) the updated data without involving service?

I tried the template with <child-template *ngIf='data' [data]='data'></child-template>

But this passes data only for 1 time. what if data gets updated in parent component?

like image 260
Sridhar Natuva Avatar asked Dec 31 '25 03:12

Sridhar Natuva


1 Answers

@Output in the ChildComponent

// ChildComponent 
@Output() OutputEvent: EventEmitter<string> = new EventEmitter();

// trigger the event to 'emit' the output event
onClick(): void {
    this.OutputEvent.emit('the string to be emitted');
}

ParentComponent

// ParentComponent view
<child-component (OutputEvent)="receiveValue($event)">

// ParentComponent controller
receiveValue($event){
    // $event is from ChildComponent = 'the string to be emitted'
}

Big Guns

Sometimes updates will not occur as you expect. Brush up on ngOnChanges to monitor for updates.

ngOnChanges(changes: SimpleChanges) {
    if ('varName' in changes) {
        // console.log(this.varName);
        // console.log(changes.varName.previousValue);
        // console.log(changes.varName.firstChange); // etc
    }
}

Two-Way Data Binding

I stay away from it. I've asked questions about it that no one seems to know the answers too regarding how to watch for its changes in the parent.

If you think you need 2WDB think about leveraging a service to sync the data via observable patterns.

CLARIFIED QUESTION: The question was clarified to parent to child cmmunication. Which is much easier. Using only @Input you can pass the child component a value with simple data-binding in the parent's view.

ChildComponent

// This property is bound using its original name.
@Input() bankName: string;

// this property value is bound to a different property name
// when this component is instantiated in a template.
@Input('originator') bankName: string;

ParentComponent view

<child-component [bankName]="parentComponentClassVariable"></child-component>
or send a string
<child-component [bankName]="'some string here'"></child-component>
like image 146
Ben Racicot Avatar answered Jan 03 '26 22:01

Ben Racicot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!