我想將一個函數傳遞給子組件。傳遞函數正常工作。問題是,如果我想更改父組件的屬性值,這將無法正常工作,因爲'this'不引用父組件,而是引用子組件(本例中爲DatagridComponent)Angular - 將函數傳遞給子組件,'this'的錯誤上下文
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>
我該如何做到這一點?
你可能想看看[分量互動]( https://angular.io/guide/component-interaction)docs,有許多不同的方法來實現父子組件之間的交互 –