1

I am adding child component dynamically to a parent. Now, in child component there is a method that is supposed to emit values back to parent, which in turn stores it to a local variable. But I get "undefined" error. It works if I add the child component in the template via its selector.

The error is the method that accepts emitted data from child component can't access class variables (this.save_data) saying "save_data" is undefined. It appears that it is looking for "save_data" in child comopnent, when it is defined in parent comopnent and accessed by a method in parent component, which is shown at the bottom end.

Hope I am making sense.

Child Component:

@Component({
  selector: 'tr[child-component]',
  templateUrl: './stock-item-form.component.html'
})
export class ChildComponent implements OnInit {

  @Input() unique_id:string='';
  @Output() eventActionHandler=new EventEmitter<any>();//

  item_brand: FormControl;

  constructor() {}

  saveRow(event){
    //emits valid data to the parent

    if(this.item_brand.valid){
      let data={'action':'add','data':{}}

      data['data']['brand']=this.item_brand.value;
      this.eventActionHandler.emit(data);

    }

  }


  ngOnInit() {

this.item_brand = new FormControl('', [Validators.required]);

  }

}

child.component.html:

   <td>
  <input type="text" class="form-control" [formControl]="item_brand"> <a href="#" (click)="saveRow($event)"><i class="fa fa-save"></i></a>  
   <div class="alert" *ngIf="!item_brand.valid && item_brand.touched">Enter brand or Unknown</div>

  </td>

Now parent component (stripped to show only relevant code). the error is now in emmitedNewAction method which can't access this.saved_data

create the child component directly:

 saved_data:any[]=[];

     @ViewChild('stockin_items_containair', {read: ViewContainerRef}) stockin_items_containair: ViewContainerRef; //dynamic stocked in item goes here

addNewChildComponent(){
   //create the child component then subscribe an event to it:

let instance=this.stockin_items_containair.createComponent(this.childComponent);



    instance.instance['eventActionHandler'].subscribe(this.emittedNewRowAction);


  }


 emittedNewRowAction($event){
//data sent from saveRow metod of child component and source of error
 console.log($event)
 console.log(this.saved_data);//saved_data undefined
    }
Nie Selam
  • 1,343
  • 2
  • 24
  • 56

0 Answers0