将数据从子组件传递到指令,然后将其传递到父组件

时间:2020-07-14 18:32:08

标签: angular components angular-directive angular2-directives angular-dynamic-components

我有一个用例,其中我必须根据某些条件渲染不同的子组件。为此,我使用了Tutorial

这里创建了一个动态表单组件,并根据某些条件,该指令加载了子组件。

我面临的问题是,在子组件中发生某些更改事件时,它必须将此信息传递给父组件。但我无法实现这一目标。

  1. 我尝试了@Output,但由于中间有一个指令,所以在父组件中未捕获发出的事件。

  2. 我尝试将服务与BehaviourSubject一起使用,但有时会触发订阅事件,因为该事件可能会导致UI更改并且数据丢失。

任何帮助将不胜感激。

示例代码:

子组件ts文件

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { ShareDataService } from '../../../../services/dataHelper/share-data.service';

@Component({
    selector: 'form-radio',
    templateUrl: './form-radio.component.html',
    styleUrls: ['./form-radio.component.scss'],
})
 export class FormRadioComponent implements OnInit {
  field;
 group: FormGroup;
 
 @Output() valuechange: EventEmitter<any> = new EventEmitter<any>();

constructor(
  private dataSharing: ShareDataService,
 ) { }

 ngOnInit() {
   
 }

  handleOnChange (event) {
      this.dataSharing.shareData(event.target.value);
     //this.valuechange.emit(event.target.value);
  }

指令代码ts文件

   @Directive({
      selector: '[dynamicField]'
   })
      export class DynamicFieldDirective implements OnInit{
   @Input() field;
   @Input() isTextField;
   @Input() group: FormGroup;
   //@Output() emitEvent: EventEmitter = new EventEmitter();
   componentRef: any;
   constructor(
        private resolver: ComponentFactoryResolver,
        private container: ViewContainerRef
   ) {}

   getValueFromComponent (event) {
        //this.emitEvent.emit(event.value);
        console.log("test directive");
   }

父组件TS文件

    export class DynamicFormComponent implements OnInit {
     @Input() config = [];

     @Input() isTextField;

     @Output() submit: EventEmitter<any> = new EventEmitter<any>();

     handleSubmit(event: Event) {
         event.preventDefault();
         event.stopPropagation();
         this.submit.emit(this.value);
     }

我已经在html文件中正确定义了。

0 个答案:

没有答案