pass value to component 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: how to pass variable via component after it's updated angular
// you can try like this, here you want to get the data from the parent component to child component, Here your parent component is ParentComponent and child component is app-child so here for getting the data from parent to child we can use ngOnChanges(changes: SimpleChanges)
// ParentComponent.html
<app-child
[data]="data"
(filterEmmiter)="filter($event)">
</app-child>
// child.component.ts
import {Component, OnChanges, SimpleChanges, Input} from '@angular/core';
class Child implements OnInit, OnChanges {
@Input() Data: any; // here is the data variable which we are getting from the parent
constructor() {}
ngOnchanges(changes: SimpleChanges) {
console.log(changes); // here you will get the data from parent once the input param is change
}
}