2017-08-15 52 views
0

我想將一個函數傳遞給子組件。傳遞函數正常工作。問題是,如果我想更改父組件的屬性值,這將無法正常工作,因爲'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> 

我該如何做到這一點?

+0

你可能想看看[分量互動]( https://angular.io/guide/component-interaction)docs,有許多不同的方法來實現父子組件之間的交互 –

回答

4

使用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. 
} 

另請參見Component Interaction

+0

謝謝您的回覆。不幸的是,在'this.onSelection.emit(item)'我得到一個錯誤:'TS2349:不能調用其類型缺少呼叫簽名的表達式。輸入'EventEmitter '沒有兼容的呼叫簽名。'任何想法爲什麼這不起作用? – RagnarLothbrok

+0

沒關係,忘記刪除括號。因此'this.onSelection.emit(item)'工作而不是'this.onSelection()。emit(item)'。謝謝。 – RagnarLothbrok

1

的問題是更多關於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 :(
} 

我們使用脂肪箭頭,以保持當前組件的情況下在函數內部