Create two @Output
properties on the child component and then use them like this:
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-key-value',
templateUrl: './key-value.component.html',
styleUrls: ['./key-value.component.css']
})
export class KeyValueComponent implements OnInit {
@Output() addClicked: EventEmitter<any> = new EventEmitter<any>();
@Output() removeClicked: EventEmitter<any> = new EventEmitter<any>();
@Input() elements;
key: '';
value: '';
constructor() { }
ngOnInit() {
}
addElemToParentArray(event) {
this.addClicked.emit();
}
rmElemFromParentArray(element) {
this.removeClicked.emit(element);
}
}
Listen to these Output
hooks in your ParentComponent TemplatE:
<app-key-value
[elements]="values"
(removeClicked)="remove($event)"
(addClicked)="addElement()">
</app-key-value>
Also in the Child Component, use the template like this:
<button (click)="addElemToParentArray($event)">Add</button>
<div *ngFor="let element of elements">
<label>key</label>
<input [(ngModel)]="element.key" type="text"/>
<label>value</label>
<input [(ngModel)]="element.value" type="text"/>
<button (click)="rmElemFromParentArray(element)">Remove</button>
</div>
Here's an Updated StackBlitz for your ref.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…