Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - Angular - passing function between components

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...