Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
252 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...