【发布时间】:2021-02-01 21:43:37
【问题描述】:
我正在尝试将异步数据从子组件传递到父组件。但是在这里console.log(this.values) 里面ngAfterViewInit() 在父组件html 页面加载中给出了一个空值。但是,如果我单击子组件中的应用按钮,它将在getValues($event) 方法打印内发出console.log(this.values); 事件。
这是我的父组件 .ts 文件
name = 'ViewUI';
@ViewChild('ChildValues', { static: false }) childReference: ChildComponent;
ngAfterViewInit() {
this.values = this.childReference.this.responseValues;
console.log(this.values);
mapResponse(this.values);
}
In here `mapResponse(this.values)` method runs before coming data from `this.values` from child component to parent.
getValues($event) {
this.values = $event;
console.log(this.values);
this.apply();
}
这是我的父组件 .html 文件
<app-child #ChildValues (getEvent)=" getValues($event)" [name]="name"></app-child>
这是我的子组件 .html 文件。
<button (click)="applyResponses()" mat-raised-button>
Apply
</button>
这是我的子组件 .ts 文件
export class ChildComponent implements OnInit {
responseValues = {
names: [], ages: []
};
@Output() getEvent = new EventEmitter < any > ();
@Input() name: string;
ngOnInit() {
this.getNames();
this.getAges();
console.log(this.name);
}
getNames() {
this.apiService.getnames(Id).subscribe((names) => {
this.responseValues.names = [names[0].name];
});
}
getAges() {
this.apiService.getages(Id).subscribe((ages) => {
this.responseValues.ages = [ages[0].age];
});
}
applyResponses() {
this.getEvent.emit(this.responseValues);
console.log(this.responseValues);
}
}
如何在父页面加载时从子组件获取数据到父组件?
【问题讨论】:
-
为什么要将数据从子组件传递给父组件?为什么不反过来呢?它将简化您的用例。
-
是的,我有父组件,并且有一个子组件可以下拉栏
标签: angular typescript angular-components viewchild asyncdata