简体   繁体   中英

How to bind two arrays using Input/Output Angular?

A component gets (via @Input()) 2 arrays: "users"

[{Id: 1, Name: 'One'}, {Id: 2, Name: 'Two'}, {Id: 3, Name: 'Three'}]

and "selectedUsers":

[{Id: 2, Name: 'Two'}]

and outputs items on a page: One Two Three

"Two" - is highlighted as it is contained in array "selectedUsers". How to add item from "users" array to "selectedUsers" and vice versa by click (and highlight clicked item)?

Parent component:

users = [
    {Id: 1, Name: 'One'}, 
    {Id: 2, Name: 'Two'}, 
    {Id: 3, Name: 'Three'}
];

usersSelected = [
    {Id: 2, Name: 'Two'}
];

HTML:

<app-item (*ngFor="let u of users", [user]="u")></app-item>

Child component:

@Input() user;
isActive: boolean = false;
toggleClass(){
    this.isActive = !this.isActive;
}

HTML

<p [class.active]="isActive" (click)="toggleClass()">{{user.Name}}</p>

Here's another try but it should be done with @Input/@Output: https://plnkr.co/edit/cjaij4aQuvN4Tk4ZE0ez?p=preview

Why do you need 2 arrays? Just extend the user type with a property named selected of type boolean (true/false). That is cleaner/easier to use then copying/removing users between the 2 arrays.

users = [
    {Id: 1, Name: 'One', IsSelected: false}, 
    {Id: 2, Name: 'Two', IsSelected: true}, 
    {Id: 3, Name: 'Three', IsSelected: false}
];

This allows any component that is used for rendering a user in the array to update the IsSelected property directly.

@Input() user;
get isActive(): boolean {return this.user.IsSelected;}

toggleClass(){
    this.user.IsSelected = !this.user.IsSelected;
}

Also I do not believe that is valid template syntax in your html.

If you like to use two arrays and a parent and child component:

https://plnkr.co/edit/uEKeMRMpLnoR49clxCfo?p=preview

@Component({
  selector: 'my-parent',
  template: `
    <my-child [users]="users" [selected]="selected" ></my-child>
  `,
})
export class ParentComponent {
  public users = ['one', 'two', 'three'  ];
  public selected = [];
}

@Component({
  selector: 'my-child',
  template: `
    <div *ngFor="let user of users">
      <p [ngClass]="{ selected: isSelected(user) }" (click)="clickOnUser(user)">{{user}}</p>
    </div>
  `,
  styles: [`
    .selected {
      color: red;
    }
  `]
})
export class ChildComponent {

  @Input()
  public users: string[];

  @Input()
  public selected: string[];

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM