簡體   English   中英

如何在父組件(Angular)中操作來自子組件的數據?

[英]How to manipulate data coming from child component in parent component (Angular)?

我有兩個組件 - 'employee-list''employee-edit'

  • employee-list : 父組件
  • employee-edit :一個子組件

<員工列表.component.html>

<button pButton type="button" (onClick)="openDialog()">
  <i class="pi pi-pencil" aria-label="Edit"></i>
</button>
<app-employee-edit></app-employee-edit>

<員工列表.component.ts>

import { EmployeeEditComponent } from '../employee-edit/employee-edit.component';

export class EmployeeListComponent implements OnInit {
  displayDialog: boolean = false;

  @Input()
  public employeeEdit!: EmployeeEditComponent;

  openDialog() {
    this.employeeEdit.displayDialog = true;
  }
}

<員工編輯.component.html>

<p-dialog
  header="{{ employeeName }}"
  [(visible)]="displayDialog"
  [style]="{ width: '50vw' }"
  [baseZIndex]="10000"
  ><p>Employee Edit</p></p-dialog
>

<員工編輯.component.ts>

@Component({
  selector: 'app-employee-edit',
  templateUrl: './employee-edit.component.html',
  styleUrls: ['./employee-edit.component.scss'],
})
export class EmployeeEditComponent {
  displayDialog: boolean = false;
}

我想操縱displayDialog ,它是布爾值,以便使用@Input()單擊時在另一個組件中打開employee-edit對話框。 但是,它沒有按預期工作。

如何在父組件中操作來自子組件的變量? 誰能幫幫我?

選項1

您想從父組件訪問子組件,但您嘗試在這種情況下使用@Input() ,這是錯誤的方法。 @Input()用於將數據從父組件傳遞到子組件。
如果你想在父組件的代碼中使用你的子組件,你必須使用@ViewChild()來獲取從父組件操作子組件的權限:

<員工列表.component.html>

<button pButton type="button" (onClick)="openDialog()">
  <i class="pi pi-pencil" aria-label="Edit"></i>
</button>
<app-employee-edit #editComponent></app-employee-edit>

<員工列表.component.ts>

import { EmployeeEditComponent } from '../employee-edit/employee-edit.component';

export class EmployeeListComponent implements OnInit {
  @ViewChild('editComponent') public employeeEdit!: EmployeeEditComponent;

  openDialog() {
    this.employeeEdit.displayDialog = true;
  }
}

選項 2

另一種選擇是將子組件中的displayDialog屬性設置為 Input 並將該屬性提供給 html 標記:

<員工列表.component.html>

<button pButton type="button" (onClick)="openDialog()">
  <i class="pi pi-pencil" aria-label="Edit"></i>
</button>
<app-employee-edit [displayDialog]="displayDialog"></app-employee-edit>

<員工列表.component.ts>

export class EmployeeListComponent implements OnInit {
  displayDialog: boolean = false;

  openDialog() {
    this.displayDialog = true;
  }
}

<員工編輯.component.ts>

@Component({
  selector: 'app-employee-edit',
  templateUrl: './employee-edit.component.html',
  styleUrls: ['./employee-edit.component.scss'],
})
export class EmployeeEditComponent {
  @Input() public displayDialog: boolean = false;
}

暫無
暫無

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

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