Привязка к встроенному компоненту в Angular 7 - PullRequest
0 голосов
/ 18 декабря 2018

В Angular (версия 7) у меня есть компонент (графики), встроенный в другой компонент (сайты):

<div class="plots" *ngIf="!selectedSiteId == ''">
  <app-plots [selectedsiteId]="this.selectedSiteId"></app-plots>
</div>

Идея состоит в том, что если пользователь выбирает просмотр графиков сайта, товстроенный компонент отображается после получения selectedSiteId.

. Эта настройка работает при первом нажатии.Но не по последующим щелчкам.Кнопка привязана к следующей функции:

  getPlots(id: number): void {
    this.selectedSiteId = id;
  }

Как я уже сказал, она работает при первом нажатии кнопки, но не при последующих нажатиях кнопок.Почему это так?

Полный код:

sites.component.ts

import { Component, Inject, OnInit, Input } from '@angular/core';
import { DataAccessService } from '../data-access.service';
import { Site } from '../site';

@Component({
  selector: 'app-sites',
  templateUrl: './sites.component.html',
  styleUrls: ['./sites.component.css']
})

export class SitesComponent implements OnInit {
  public sites: Site[];
  public selectedSiteId: number = 0;
  constructor(private dataAccessService: DataAccessService) { }

  ngOnInit() {
    this.getSites();
  }

  getPlots(id: number): void {
    this.selectedSiteId = id;
  }

  getSites(): void {
    this.dataAccessService.getSites()
        .subscribe(sites => this.sites = sites);
  }
}

sites.component.html

<table class='table' *ngIf="sites">
  <thead>
    <tr>
      <th>ID</th>
      <th>Site</th>
      <th>Postcode</th>
      <th>Plots</th>
      <th>Plots Completed</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let site of sites">
      <td>{{ site.id }}</td>
      <td>{{ site.siteName }}</td>
      <td>{{ site.sitePostCode }}</td>
      <td>{{ site.plotCount }}</td>
      <td>{{ site.plotCompletedCount }}</td>
      <!-- <td>{{ site.plots.length }}</td> -->
      <td><button (click)="getPlots(this.site.id)">Show Plots</button></td>
    </tr>
  </tbody>
</table>


<div class="plots" *ngIf="!selectedSiteId == ''">
  <app-plots [selectedsiteId]="this.selectedSiteId"></app-plots>
</div>


<div class="plots" *ngIf="!selectedSiteId == ''">
  <app-plots [selectedsiteId]="this.selectedSiteId"></app-plots>
</div>

plots.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { DataAccessService } from '../data-access.service';
import { Plot } from '../site';

@Component({
  selector: 'app-plots',
  templateUrl: './plots.component.html',
  styleUrls: ['./plots.component.css']
})

export class PlotsComponent implements OnInit { 

  public plots: Plot[];
  @Input() selectedsiteId: number;

  constructor(private dataAccessService: DataAccessService) { }

  ngOnInit() {
    this.getPlots(this.selectedsiteId);
  }

  getPlots(id: number): void {
    alert(id);
    this.dataAccessService.getPlots(id)
      .subscribe(plots => this.plots = plots);
  }

  loadPlotDetails(id: number): void {
  }
}

plots.component.html

<table class='table' *ngIf="plots">
  <thead>
    <tr>
      <th>ID</th>
      <th>Name</th>
      <th>Site</th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let plot of plots">
      <td>{{ plot.id }}</td>
      <td>{{ plot.name }}</td>
      <td>{{ plot.site }}</td>
      <a routerLink="/plot-detail">Details</a>
    </tr>
  </tbody>
</table>

1 Ответ

0 голосов
/ 18 декабря 2018

Вам необходимо вызвать метод getPlots () внутри хуков жизненного цикла ngOnChanges.Всякий раз, когда значение @Input изменяется, вызывается ngOnChanges.

import { Component, OnInit, Input } from '@angular/core';
import { DataAccessService } from '../data-access.service';
import { Plot } from '../site';

@Component({
  selector: 'app-plots',
  templateUrl: './plots.component.html',
  styleUrls: ['./plots.component.css']
})

export class PlotsComponent implements OnInit { 

  public plots: Plot[];
  @Input() selectedsiteId: number;

  constructor(private dataAccessService: DataAccessService) { }

  ngOnInit() {
    this.getPlots(this.selectedsiteId);
  }

  ngOnChanges() {
    this.getPlots(this.selectedsiteId);
  }

  getPlots(id: number): void {
    alert(id);
    this.dataAccessService.getPlots(id)
      .subscribe(plots => this.plots = plots);
  }

  loadPlotDetails(id: number): void {
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...