Angular 10 父组件调用子组件函数无法生效问题咨询
根本原因
你遇到的调用失效问题主要是以下几个原因共同导致的:
- 父组件在constructor生命周期操作子组件实例,此时子组件还未渲染完成,
this.child为undefined,调用方法直接报错 - 变量名大小写不匹配、笔误产生的未定义变量导致逻辑中断
- 子组件没有接收父组件的选中类型参数,就算方法调用成功也无法查询对应数据
- 下拉框属性绑定位置错误,选择值变更事件根本不会触发
修复方案
1. 修正父组件模板写法
把下拉框的属性放回选择器组件内部,同时给子组件绑定输入属性传递选中的用户类型ID:
<!-- 以下是示例,将属性放回你实际使用的下拉组件标签内部即可 --> <nz-select [items]="userTypeSelectItems" [(ngModel)]="userTypeId" id="fieldType" bindLabel="value" bindKey="key" (change)="changeUserType()" [clearable]="false" > </nz-select> <!-- 给子组件传入选中的用户类型ID --> <app-user-list [userTypeId]="userTypeId"></app-user-list>
2. 修正父组件TS逻辑
- constructor仅用来做依赖注入,业务逻辑移到
ngOnInit生命周期执行 - 修正变量名笔误,添加可选链避免子组件未初始化时调用报错
export class LoginScreenComponent implements OnInit { @ViewChild(UserListComponent) child: UserListComponent; userTypeSelectItems: Array<SelectItem>; userTypeId: any; items: any; constructor( private userTypeSettingsService: userTypeSettingsService, ) {} ngOnInit() { this.userTypeSettingsService.getuserTypes().subscribe((data) => { this.userTypeSelectItems = data; if (this.userTypeSelectItems && this.userTypeSelectItems.length > 0) { this.userTypeId = this.userTypeSettingsService.selectedContractTypeId ?? this.userTypeSelectItems[0].key; // 修正笔误:替换未定义的this.contractTypeId为正确变量 this.userTypeSettingsService.setContractTypeId(this.userTypeId); this.userTypeSettingsService.fillSelectedFields(this.userTypeId).subscribe(dataFields => { this.items = dataFields; // 异步回调执行时子组件已渲染完成,实例存在 this.child?.getUser(); }); } }); } changeUserType() { this.child?.getUser(); } }
3. 修正子组件TS逻辑
- 添加
@Input()装饰器接收父组件传递的用户类型ID - 修正方法内部的未定义变量笔误
import { Input } from '@angular/core'; // 子组件类内部定义输入属性 @Input() userTypeId: any; getUser() { this.loading = true; this.userService .getAllUsers(this.userTypeId) .pipe(finalize(() => (this.loading = false))) .subscribe( (data) => { this.rows = data.map(notif => { return { // 修正笔误:从遍历项取status_id,不要直接用未定义变量 user_status_id: notif.status_id, } }); }, (err) => this.toastr.error(err), () => (this.loading = false) ); }
内容的提问来源于stack exchange,提问作者salma
相关产品推荐
相关产品推荐

