代码之家  ›  专栏  ›  技术社区  ›  Zabs

不确定为什么数据不能在Angular 4中正确地从子组件传递到父组件

  •  0
  • Zabs  · 技术社区  · 6 年前

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

    函数 applyGif()

    注意-组件有一些不需要的代码在这篇文章中从视图中删除,以获得额外的清晰度。

    下面的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,
      ) {}
    }
    

    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>
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Huske Metalhead1247    6 年前

    你用过吗 @Output() 把信息从孩子传给父母 applyGif()

    在你的 GifPickerComponent 声明:

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

    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);
    }
    

    PostingComponent 正在使用的HTML模板文件 app-gifpicker :

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

    创建 onGifSelected

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

    此外,您的发布组件是父组件,它承载其他组件,如您的 GIFPickerComponent