< Angular komponensek kommunikációja
Az @Input és @Output dekorátorok segítéségével függvényeket hívhatunk egy másik komponensben, ha a két komponens szülő-gyermek viszonyban van, és nem az AppComponet-ben van a hívandó függvény.
Legyen egy weboldal amely termékeket tartalmaz.
ng generate component emps ng generate component empdet
//... export class EmployeesComponent implements OnInit { employeeName = "Erős István"; constructor() { } ngOnInit(): void { } }
<p>employees works!</p> <app-empldet [employeeName]="employeeName"></app-empldet>
import { Component, Input, OnInit } from '@angular/core'; //... export class EmpldetComponent implements OnInit { @Input() employeeName = ''; constructor() { } ngOnInit(): void { } }
<p>empldet works!</p> Név: {{employeeName}}
Teljes:
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-emps', templateUrl: './emps.component.html', styleUrls: ['./emps.component.css'] }) export class EmpsComponent implements OnInit { actName = "Erős István"; constructor() { } ngOnInit(): void { } }
<p>emps works!</p> <app-empdet [employeeName]="actName"></app-empdet>
import { Component, Input, OnInit } from '@angular/core'; @Component({ selector: 'app-empdet', templateUrl: './empdet.component.html', styleUrls: ['./empdet.component.css'] }) export class EmpdetComponent implements OnInit { @Input() employeeName = ''; constructor() { } ngOnInit(): void { } }
<p>empdet works!</p> Név: {{employeeName}}
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-emps', templateUrl: './emps.component.html', styleUrls: ['./emps.component.css'] }) export class EmpsComponent implements OnInit { employeeArray = [ 'Kerek György', 'Rendes Imre' ]; constructor() { } ngOnInit(): void { } addEmployee(newEmployee: string) { this.employeeArray.push(newEmployee); } }
import { Component, EventEmitter, OnInit, Output } from '@angular/core'; @Component({ selector: 'app-empdet', templateUrl: './empdet.component.html', styleUrls: ['./empdet.component.css'] }) export class EmpdetComponent implements OnInit { @Output() newEmployeeEvent = new EventEmitter<string>(); constructor() { } ngOnInit(): void { } addNewEmployee(value: string) { this.newEmployeeEvent.emit(value); } }