如何在父组件(Angular)中操作来自子组件的数据?



我有两个组件'employee-list''employee-edit'

  • employee-list:父组件
  • employee-edit:子组件

& lt; employee-list.component.html>

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

& lt; employee-list.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;
}
}

& lt; employee-edit.component.html>

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

& lt; employee-edit.component.ts>

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

我想操纵displayDialog,这是布尔值,以便employee-edit对话框在另一个组件中打开点击使用@Input()。然而,它并没有像预期的那样工作。

如何在父组件中操作来自子组件的变量?有人能帮帮我吗?

选项1

你想从父组件访问子组件,但你试图使用@Input()在这种情况下,什么是错误的方式。@Input()用于将数据从父组件传递给子组件。
如果你想在父组件的代码中使用子组件,你必须使用@ViewChild(),它用于从父组件获得操作子组件的访问权限:

& lt; employee-list.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>

& lt; employee-list.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标签:

& lt; employee-list.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>

& lt; employee-list.component.ts>

export class EmployeeListComponent implements OnInit {
displayDialog: boolean = false;
openDialog() {
this.displayDialog = true;
}
}

& lt; employee-edit.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;
}

相关内容

  • 没有找到相关文章

最新更新