2017-08-15 82 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 :(
} 

我们使用脂肪箭头,以保持当前组件的情况下在函数内部