我有两个组件父组件(登录屏幕)和一个子组件(用户列表)。父组件具有下拉列表。网格根据下拉列表中选择的项加载,我需要激发子组件的函数,但这对我不起作用。我有以下代码:父组件html:
I have the following code:
<div>[items]="UserTypeSelectItems"[(ngModel)]="UserTypeId" id="fieldType"
bindLabel="value" bindKey="key" (change)="changeUserType()" [clearable]="false">
</div>
<app-user-list></app-user-list>父组件ts:
我有以下代码:
export class Login-ScreenComponent implements OnInit {
@ViewChild(UserListComponent)child:UserListComponent;
userTypeSelectItems: Array<SelectItem>;
userTypeId: any;
items: any;
constructor(
private userTypeSettingsService: userTypeSettingsService,
) {
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.userTypeSettingsService.setContractTypeId(this.contractTypeId);
this.userTypeSettingsService.fillSelectedFields(this.userTypeId).subscribe(dataFields => {
this.items = dataFields;
this.child.getUser();
});
}
});
}
changeUserType() {
this.child.getUser();
}子组件ts:
我有以下代码:
getUser() {
this.loading = true;
this.userService
.getAllUsers(this.userTypeId)
.pipe(finalize(() => (this.loading = false)))
.subscribe(
(data) => {
this.rows = data.map(notif => {
return {
user_status_id: status_id,
});
},
(err) => this.toastr.error(err),
() => (this.loading = false)
);}‘
发布于 2021-11-13 22:03:35
如果我没理解错你的问题,这就是我的建议
父HTML
<div>[items]="UserTypeSelectItems"[(ngModel)]="UserTypeId" id="fieldType"
bindLabel="value" bindKey="key" (change)="changeUserType()" [clearable]="false">
</div>
<app-user-list [userTypeId]="userTypeId"></app-user-list>在父ts中,删除this.child.getUser()
在子组件中,您应该有带有设置器的输入参数userTypeId。它将在每次值发生更改时调用getUser()函数。
private _userTypeId: number;
@Input()
get userTypeId(): number {
return this._userTypeId;
}
set userTypeId(value: number): void {
this._userTypeId = value;
this.getUser();
}您还可以使用将注入到父组件和子组件中的外部服务,或者使用父组件中的某个主题,创建其可观察的基础,并将其作为输入参数发送给子组件。在那里,您订阅了observable,然后您需要使用subjectvar.next(value)发出值,并将调用as result函数。如果你需要的话,我可以写下这个例子。
UPD:使用可观察对象的示例
父组件ts文件:
private userTypeIdSubject$ = new Subject<string>();
private userTypeId$ = this.userTypeIdSubject$.asObservable();
changeUserType(): void {
// some code goes here
this.userTypIdSubject$.next(userTypeId); // this should send the message to the observer (child)
}父HTML:
<div>[items]="UserTypeSelectItems"[(ngModel)]="UserTypeId" id="fieldType"
bindLabel="value" bindKey="key" (change)="changeUserType()" [clearable]="false">
</div>
<app-user-list [userTypeObservable]="userTypeId$"></app-user-list>子TS
@Input()
userTypeObservable: Observable<string>;
ngOnInit() {
if(this.userTypeObservable) {
this.userTypeObservable.subscribe(
(userTypeId) => {
this.userTypeId = userTypeId;
this.getUser();
}
}
}
}https://stackoverflow.com/questions/69957793
复制相似问题