0

I have a parent and a child components:

Parent JS

export class ListComponent {
  public users = [{Id: 1, Name: 'One'}, {Id: 2, Name: 'Two'}, {Id: 3, 
Name: 'Three'}];
  public selected = [{Id: 2, Name: 'Two'}];}

Parent HTML

my-child([users]="users", [selected]="selected")

Child JS

export class ChildComponent {

@Input() public users: string[];

@Input() public selected: string[];

public isSelected(user.Name) { 
  return this.selected.indexOf(user) !== -1;
}

public clickOnUser(user.Name) {
  if (this.selected.indexOf(user.name) !== -1) {
      this.selected.splice(this.selected.indexOf(user.Name), 1);
    } else {
      this.selected.push(user.Name);
    }
  }

}

Child HTML

div(*ngFor="let user of users")
  p(
    [ngClass]="{ selected: isSelected(user.Name) }", 
    (click)="clickOnUser(user)") {{user.Name}}

I need the second item in a list to be selected by default (I have a class 'selected' in my SASS file for that). For now there's an error in IDE:

"public isSelected(user.Name) {" - dot is highlighted, because comma expected.

"public clickOnUser(user.Name) {" - the same error.

Here we can see almost identical example and it works fine (the difference in this case is in the arrays - they don't contain objects). So, how to make the second item in my list selected by default?

rinatoptimus
  • 427
  • 1
  • 5
  • 21

1 Answers1

1

All you need to do is :

user.Name to user in your Template and Component

Solution to 2nd Object was not selected by default ,

export class ParentComponent {
  public users = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: 'three'}];
  public selected = [];

  constructor(){
    this.selected.push(this.users[1]);
  }
}

Reason behind this is very interesting : How to determine equality for two JavaScript objects?

As per the doc indexOf :

indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

WORKING DEMO (With Array Storing Object)


For More Detail Run The Below Snippet :

var a = {Id: 2, Name: 'Two'};
var b = {Id: 2, Name: 'Two'};
var c = a;

console.log('Same Obejct But not equal (Not Strickly) --> ' ,a==b);
console.log('Same Obejct But not equal (Strickly) --> ',a===b);
console.log('But Here it will work cause of refernce --> ',a==c);
console.log('Same for Strickly --> ',a===c);
Vivek Doshi
  • 56,649
  • 12
  • 110
  • 122
  • Thank you, but how to make the second element selected by default? It should be red. By the way, in your plunker clicks work fine, but if I click elements in my local app elements remain black. – rinatoptimus Feb 26 '18 at 07:45
  • Sorry, clicks work as it meant to. But the second element is still not selected by default. – rinatoptimus Feb 26 '18 at 07:55