我正在动态地将子组件添加到父组件 . 现在,在子组件中有一个方法应该将值发送回父级,而父级又将其存储到本地变量 . 但我得到“未定义”错误 . 如果我通过其选择器在模板中添加子组件,它可以工作 .
错误是接受来自子组件的发出数据的方法无法访问类变量(this.save_data),说“save_data”未定义 . 它似乎在子comopnent中寻找“save_data”,当它在父comopnent中定义并由父组件中的方法访问时,它显示在底端 .
希望我有意义 .
子组件:
@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>
现在是父组件(剥离以仅显示相关代码) . 错误现在在emmitedNewAction方法中,无法访问this.saved_data
直接创建子组件:
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
}