javascript - 不确定为什么 Angular 4 中的数据无法从子组件正确传递到父组件

标签 javascript angular components angular4-forms

我有两个组件,并且希望从“子”组件传递数据,当用户单击该组件中的图像时,就会发生这种情况。

我有两个组件(发布和 gifpicker - 子组件)

函数 applyGif() 是我用来传递数据的子组件中的函数 - 我想将此数据传递给父组件。

注意 - 为了更加清晰起见,组件中的一些此方面不需要的代码已从本文中删除。

由于 View 中的某种原因,下面的 HTML 组件当前在 selectedGif 中不显示任何内容

-- 发布组件(父组件)--

/** long list of imports here **/
@Component({
selector: 'app-posting',
templateUrl: './posting.component.html',
styleUrls: ['./posting.component.scss'],
providers: [ GifpickerService ],
})
export class PostingComponent implements OnInit{

  public selectedGif: any = '';
  @ViewChild(GifpickerComponent) gifpicker: GifpickerComponent;

  ngOnInit(): void {

  }

  constructor(@Inject(DOCUMENT) private document: any,
      public gifpickerService: GifpickerService,
  ) {}
}

-- GifPickerComponent(子组件)--

import {Component, OnInit} from '@angular/core';
import {FormControl} from '@angular/forms';
import {GifpickerService} from "./gifpicker.service";

@Component({
  selector: 'app-gifpicker',
  templateUrl: './gifpicker.component.html',
  styleUrls: ['./gifpicker.component.scss'],
  providers: [ GifpickerService ],
})
export class GifpickerComponent implements OnInit {
  public selectedGif: any = {};

 constructor(private gifpickerService: GifpickerService) {}

 ngOnInit() {

 }

  applyGif(gif): any {
    // this is an json object I want to use/see in the Posting HTML Component 
    let gifMedia = gif.media[0]; 
  }
}

-- 发布组件 HTML(需要来自此处显示的 gifPickerComponent applyGif() 的数据 --

<div>{{ selectedGif }}</div>

最佳答案

您是否尝试过在 applyGif() 方法结束后使用 @Output() 将信息从子级传递给父级。

在您的 GifPickerComponent 中声明:

@Output() gifSelected: EventEmitter<any> = new EventEmitter<any>(); // or whatever type your are sending

applyGif() 中选择 GIF 后

applyGif(gif): any {
    this.gifPickerVisible = false;
    this.uploadedGif = true;
    let gifMedia = gif.media[0]; // this is an json object I want to use/see in the Posting HTML Component 
    this.gifSelected.emit(gifMedia);
}

在您使用 app-gifpickerPostingComponent HTML 模板文件中:

<app-gifpicker (gifSelected)="onGifSelected($event)"></app-gifpicker>

在 posts.component.ts 文件中创建 onGifSelected 并处理结果:

public onGifSelected(gif: any) {
    // Do whatever you need to do.
    this.selectedGif = gif;
}

此外,您的发布组件是父组件,它托管其他组件,例如您的 GIFPickerComponent,无需在两个组件中都提供服务。在父组件中执行此操作就足够了,并且它将传递给子组件。换句话说,将传递同一个实例。根据您当前的安排,父级和子级都有两个不同的服务实例。

关于javascript - 不确定为什么 Angular 4 中的数据无法从子组件正确传递到父组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52651013/

相关文章:

angular - ng用于重复组件

javascript - 用于 Web 应用程序开发的 sproutcore 与 javascriptMVC 对比

javascript - 如何用 Promises 写这个?

jQuery::Ajax 永远不会成功

typescript - 使用数字管道抛出 InvalidPipeArgumentException(管道 '1' 的无效参数 'DecimalPipe')

asp.net-mvc - MVC 组件 GUI 方法

javascript - 我如何使用 jQuery 从 LastFM 解析这个特定的 JSON 数据?

html - Angular - 基于用户输入的构建表单

javascript - AWS Cognito - SerializationException(在不期望的位置找到结构或 map 的开始)

vue.js - Vue 动态组件和动态 props