簡體   English   中英

Angular 10:從父組件調用子組件函數

[英]Angular 10: Call a child component function from parent component

我有 2 個組件父級(登錄屏幕)和一個子級(用戶列表)。 父組件有下拉列表。 網格根據下拉列表中選擇的項目加載我需要觸發子組件的功能,這對我不起作用。 我有以下代碼:父組件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)
  );

} '''''''

如果我正確理解你的問題,那就是我的建議

父 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() 的所有調用

在子組件中,您應該使用 setter 輸入參數userTypeId 每次更改值時,它都會調用getUser()函數。

private _userTypeId: number;
@Input() 
get userTypeId(): number {
  return this._userTypeId;
}
set userTypeId(value: number): void {
  this._userTypeId = value;
  this.getUser();
}

您還可以使用將被注入到父組件和子組件中的外部服務或在父組件中使用一些 Subject,創建它的 Observable 基礎,它將作為輸入參數發送給子組件。 在那里你訂閱了 observable,然后你需要用subjectvar.next(value)發出值,結果函數將被調用。 如果你需要,我可以寫下這個例子。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM