简体   繁体   中英

Angular 6 - passing data between components

I am learning angular 6 and typescript and have some problems with passing data between multiple components. It looks like on "expense-box.component.ts" component "this.participants" in ngOnInit method is null/empty. So I am not getting any data.

First (parent) component - expense.component.ts :

public participants = new Array<Participant>();

getParticipants(): void {
    this.participantService
      .getParticipants(token)
      .subscribe(participants => (this.participants = participants));
}

Participant service - participant.service.ts (to show whats inside getParticipants method)

  getParticipants(token: string): Observable<Participant[]> {
    return this.http.get<Participant[]>(`${this.url}/${token}`).pipe(
      tap(() => this.log(`Participants assigned to trip with token: ${token} fetched`)),
      catchError(this.handleError<Participant[]>('getParticipants'))
    );
  }

It's html template - expense.component.html :

<app-expense-box *ngIf="selectedSplitTab == 1" [participants]="participants"></app-expense-box>

expense-box.component.ts

export class ExpenseBoxComponent implements OnInit {
  @Input() participants: Participant[];
  public equallyList = new Array<Equally>();

  ngOnInit() {
    this.participants.forEach(element => {
      this.equallyList.push(new Equally(element.id, false, element.name));
    });
  }

  addExpense(): void {
    this.expense.equallyTab = this.equallyList;
    this.expenseService.addExpense(this.expense).subscribe(() => console.log('Expense added!'));
  }
}

It's html template - expense-box.component.html

<app-split-differently [equallyList]="equallyList" [splitEqually]="splitEqually"></app-split-differently>

It's child component - split-differently.component.ts

export class SplitDifferentlyComponent implements OnInit {
  @Input() splitEqually: boolean;
  @Input() equallyList: Equally[];

  public selectedSplitTab = 1;

  constructor() {}

  ngOnInit() {}

  enableSplitTab(selectedTab: number): void {
    this.selectedSplitTab = selectedTab;
  }
}

It's html template - split-differently.component.html

<div class="form-check" *ngFor="let item of equallyList">
  <input class="form-check-input" type="checkbox" value="" id="equallyTabParticipant{{item.userId}}" checked="{{item.checked}}">
  <label class="form-check-label" for="equallyTabParticipant{{item.userId}}">
    {{ item.userName }}
  </label>
  <hr>
</div>

In the end I want to have current state of EquallyList while sending it to the backend. Now nothing is even displayed, because I am doing something wrong (console not logging any errors).

Thanks to the answers in comments everything is displayed correctly now. I've checked one checkbox (other are unselected), clicked save button and all "checked" are set to false so values not binded properly. Here is screen with json which is sent to back-end:

在此处输入图片说明

Your input might not received the data when you are trying to access it in ngOnInit() method.

You should use the setter method for your input and then do your stuff in that method. Alternatively you can use ngOnChanges() hook

for ex: with setter

@Input() myInput: any;

 set myInput() {
    //Do stuff here
}

with ngOnchanges

ngOnChanges(changes: SimpleChange){
if(changes['myInput']){
//Do stuff here
}
}

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