我正在尝试将函数传递给子组件。传递函数工作正常。问题是,如果我想更改父组件的属性值,这不会起作用,因为这个'不是引用父组件,而是引用子组件(在我的情况下是DatagridComponent)
this
的背景似乎是个问题。请参阅下面的代码中的注释。
父组件:
@Component({
selector: 'app-user-management',
templateUrl: './user-management.component.html',
styleUrls: ['./user-management.component.css'],
})
export class UserManagementComponent implements OnInit {
showUserDetails: boolean: false;
showUsergroupDetails = false;
onSelectUser() {
this.showUsergroupDetails = false;
this.showUserDetails = true;
console.log(this.showUsergroupDetails); // prints false, as expected
console.log(this.showUserDetails); // prints true, as expected
console.log(this); // prints DatagridComponent :(
}
HTML,将onSelectUser作为函数传递:
<app-datagrid [onSelection]="onSelectUser"></app-datagrid>
子组件:
@Component({
selector: 'app-datagrid',
templateUrl: './datagrid.component.html',
styleUrls: ['./datagrid.component.css']
})
export class DatagridComponent implements OnInit {
@Input() onSelection: () => {};
onSelectListItem(item: any) {
// some code
if (this.onSelection) {
this.onSelection(); // is executed, results see comments in parent component
}
}
}
子组件的HTML:
<div *ngFor="let item of items" (click)="onSelectListItem(item)">
....
</div>
我该如何做到这一点?
答案 0 :(得分:8)
使用Output
事件从子组件到父组件进行通信。使用Input
属性绑定将数据从parent
传递给子
<强> HTML 强>
<app-datagrid (onSelection)="onSelectUser($event)"></app-datagrid>
组件
@Component({
selector: 'app-datagrid',
templateUrl: './datagrid.component.html',
styleUrls: ['./datagrid.component.css']
})
export class DatagridComponent implements OnInit {
@Output() onSelection: EventEmitter<any> = new EventEmitter();
onSelectListItem(item: any) {
this.onSelection.emit(item);
}
}
//app-user-management method will receive item object
onSelectUser(item: any) {
//here you would have item object.
}
答案 1 :(得分:4)
问题更多的是关于this
上下文,您可以通过这种方式修复它:
onSelectUser = ()=>{ // note this part
this.showUsergroupDetails = false;
this.showUserDetails = true;
console.log(this.showUsergroupDetails); // prints false, as expected
console.log(this.showUserDetails); // prints true, as expected
console.log(this); // prints DatagridComponent :(
}
我们使用胖箭头将当前组件的上下文保留在函数
中