I have 2 components: AppComponent and ChildComponent. ChildComponent is the child component of AppComponent. How to to send altered "variable1" from ChildComponent back to AppComponent?
AppComponent [html]:
<child [variable1]="variable1">PARENT</child>
AppComponent [ts]:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
variable1: string = 'abc';
}
ChildComponent [ts]:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent {
@Input('variable1') variable1: string;
ngOnInit() {
this.variable1 = this.variable1 + 'def';
}
}
You can do this with an EventEmitter
and @Output
and marking two-way-binding in your child tag. So your child tag add two-way-binding:
<child [(variable1)]="variable1">PARENT</child>
in your child mark this event emitter with the variable name, and suffix Change
(important for two-way-binding to work!)
@Input() variable1: string;
@Output() variable1Change = new EventEmitter<string>()
and whenever you want to pass the variable change to parent, in child do:
this.variable1Change.emit('my new value')
As a sidenote, notice I removed the alias from your @Input
, this based on the docs style guide: https://angular.io/guide/styleguide#avoid-aliasing-inputs-and-outputs