将功能传递给子组件,"this"的错误上下文 [英] Passing function to child component, wrong context of 'this'

查看:69
本文介绍了将功能传递给子组件,"this"的错误上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将功能传递给子组件.传递函数工作正常.问题是,如果我想更改父组件的属性值,这将无法正常工作,因为"this"不是指父组件,而是子组件(在我的情况下为DatagridComponent)

I am trying to pass a function to a child component. Passing the function works fine. Problem is, if I want to change property values of the parent component, this wont work since 'this' is not referencing to the parent component, but to the child component (DatagridComponent in my case)

this的上下文似乎是问题所在.请参见下面的代码中的注释.

The context of this seems to be the problem. See comments in code below.

父组件:

@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作为函数传递:

HTML, passing onSelectUser as function:

<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>

我该怎么做?

推荐答案

问题更多地是关于this上下文的问题,您可以通过以下方式解决它:

The question is more about this context, which you can fix it this way :

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 :(
}

我们使用粗箭头将当前组件的上下文保留在函数中

We're using fat arrow to keep the context of the current component inside the function

这篇关于将功能传递给子组件,"this"的错误上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆