Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing function to child component, wrong context of 'this'

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)

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

Parent component:

@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, passing onSelectUser as function:

<app-datagrid [onSelection]="onSelectUser"></app-datagrid>

Child component:

@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 of child component:

<div *ngFor="let item of items" (click)="onSelectListItem(item)">
   ....
</div>

How can I accomplish this?

like image 322
RagnarLodbrok Avatar asked Aug 15 '17 09:08

RagnarLodbrok


People also ask

How do you pass data to a child component?

To let Angular know that a property in a child component or directive can receive its value from its parent component we must use the @Input() decorator in the said child. The @Input() decorator allows data to be input into the child component from a parent component.

How do you communicate between parent and child components?

@Input() and @Output() give a child component a way to communicate with its parent component. @Input() lets a parent component update data in the child component. Conversely, @Output() lets the child send data to a parent component.


1 Answers

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

like image 123
Milad Avatar answered Nov 16 '22 03:11

Milad