Angular - passing function between components

2019-09-21 00:22发布

问题:

Here is my issue skeleton: https://stackblitz.com/edit/angular-jk8dsj

I have two problems in this task:

  1. I want to add element in app.component, when I clicking the button from key-value.component. I do not know how to do it. I'm trying to passing using @Output() decorator, bo it did not work. I think it I think it has to be something like:

    <app-key-value [elements]="values"
           (addElemToParentArray)="???"
           (rmElemFromParentArray)="???"></app-key-value>
    
  2. Later I want send this values array to the server. For now in my app component function pushing elements to the array with emty Element values: key: '' and value: ''. How to make the values in the table correspond to the entered input values? I'm trying using ngModel, but values filled after the empty values element push to the array. Do I have to create another Array which is created on submit whole page and sending data to server?

回答1:

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.