child to parent communication in angular code example
Example 1: angular @Output()
// Parent Component
import { Component } from '@angular/core'
@Component({
selector: app-component,
template:
`
<app-item-output (newItemEvent)='addItem($event)'> </app-item-output>
<ul>
<li *ngFor='let item of items'>{{item}}</li>
</ul>
`
})
export class AppComponent {
items = ['item1', 'item2', 'item3'];
addItem(newItem: string){
this.items.push(newItem);
}
}
// Child Component
import { Output, EventEmitter } from '@angular/core';
@Component({
selector: app-item-output,
template:
`
<label>Add an item: <input #newItem></label>
<button (click)='addNewItem(newItem.value)'>Add to parent's list</button>
`
})
export class ItemOutputComponent {
@Output() newItemEvent = new EventEmitter<string>();
addNewItem(value: string) {
// this method emits the value of newItemEvent
this.newItemEvent.emit(value);
}
}
Example 2: angular send data to parent component
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<button (click)="sendMessage()">Send Message</button>
`,
styleUrls: ['./child.component.css']
})
export class ChildComponent {
message: string = "Hola Mundo!"
@Output() messageEvent = new EventEmitter<string>();
constructor() { }
sendMessage() {
this.messageEvent.emit(this.message)
}
}
Example 3: input property angular
//passing properties to child elements
<app-slider [title]="'This is a title'"> </app-slider>
//inside the component slider i add just before the constructor :
.
.
@input() title: string;
constructor(){
}
//after this we can use these new property inside the .html file of the component
<div id='slider' class='slider-big'>
<h1> {{title}}</h1>
</div>