我有一个组件,它是一种表单,提交后会插入数据库中。而且我需要重新列出数据库中更改的数据。该列表方法在另一个组件中找到。 我尝试使用viewChild调用这些函数,但提交时ViewChild看起来未定义。
这是在html中列出数据的数据组件
private void BtnChangeLanguageToEnUs_Click(object sender, RoutedEventArgs e)
{
LocUtil.SwitchLanguage(this, "en-US");
}
这是表单的checkComponent。
export class DataComponent implements OnInit{
constructor(private dataService: DataService,private router:Router) {
this.getData();
}
ngOnInit(): void {
}
getData(){
this.dataService.getData().subscribe(
resp => this.data = resp,
error =>console.log(error)
);
}
detail(id: number){
this.router.navigate(['data/check' + id]);
}
}
是否有一种方法可以调用ViewChild之外的其他组件的功能?还是我执行错了?我需要访问DataComponent的函数 getData()
答案 0 :(得分:0)
如果DataComponent是CheckComponent的子级,我的建议是使用自上而下的方法/单向数据绑定到数据流。那是:
在CheckComponent上更新数据时,将进行更改检测。这会将更新后的数据向下传递到DataComponent,DataComponent将自动更新其视图。
这是您要实现的正确方法。
答案 1 :(得分:0)
ViewChildren
为您提供了QueryList
,而不是组件的单个实例。
import {QueryList} from '@angular/core';
...
ViewChildren(DataComponent) dataComponent: QueryList<DataComponent>;
是正确的输入方式... QueryList
API与js数组API共享许多功能,让您做到这一点...
this.dataComponent.forEach(dc => dc.getData());
QueryList
文档:https://angular.io/api/core/QueryList
ViewChild
将为您提供页面上子组件的第一个实例
ViewChild(DataComponent, {static: false}) dataComponent: DataComponent;
如果您只有/想要一个,这将使您可以像在问题中一样访问DataComponent
。