无法从哑组件获取事件

时间:2018-12-09 02:38:32

标签: angular typescript

我无法从哑组件中获取事件。我认为它正在运行,但未将事件绑定到智能组件。输出正常,但是当我更改事件的值时不起作用,并且没有显示错误。

// planet-data.component.html(智能组件)

<div class="main">
    <app-loading *ngIf="loading"></app-loading>
    <app-planet-view [pics]="pics" class="fixed" (selected)="onSelect($event)"></app-planet-view>
</div>

// planet-data.component.ts

onSelect(event: Cam) {
    if (event.name === 'CHEMCAM') {
      this.loading = true;
      this.getCamType();
    } else {
      this.loading = true;
      event.name === 'NAVCAM' ? this.getCamType('spirit', 'navcam') : this.getCamType('opportunity', 'fhaz');
    }
  }

// dropdown-menu.component.html(哑巴组件)

<p-dropdown [options]="cameras" [(ngModel)]="selectedCam" placeholder="Select a Cam" optionLabel="name"
            (ngModelChange)="getDisplayCam($event)">
</p-dropdown>

// dropdown-menu.component.ts

getDisplayCam(event: Cam) {
    this.selected.emit(event);
  }

// planet-view.component.html(另一个Dumb组件)

<div *ngIf="pics">
  <div *ngFor="let pic of pics.photos">
    <div class="card" style="width: 16rem;">
      <img class="card-img-top" src="{{pic.img_src}}" alt="Card image cap">
      <p>{{pic.earth_date | date}}</p>
    </div>
  </div>
  <h4>{{title}}</h4>
  <app-dropdown-menu></app-dropdown-menu>
</div>

1 个答案:

答案 0 :(得分:0)

您没有在selected中发出PlanetViewComponent事件。实际的selected事件是从DropdownMenuComponent引发的。如果您不会从selected发出PlanetViewComponent事件,那么您将无法在PlanetDataComponent中收听它。

planet-view.component.html的代码。

<div *ngIf="pics">
  <div *ngFor="let pic of pics.photos">
    <div class="card" style="width: 16rem;">
      <img class="card-img-top" src="{{pic.img_src}}" alt="Card image cap" routerLink="/detail">
      <p>{{pic.earth_date | date}}</p>
    </div>
  </div>
  <!-- Added catching (selected) event -->
  <app-dropdown-menu (selected)="selected.emit($event)"></app-dropdown-menu>
</div>

planet-view.component.ts的代码如下。

@Component({
  selector: 'app-planet-view',
  templateUrl: './planet-view.component.html',
  styleUrls: ['./planet-view.component.sass']
})
export class PlanetViewComponent implements OnInit {

  @Input() pics: Photo;

  // Added @Output() event
  @Output() selected = new EventEmitter<Cam>();
  constructor() {}

  ngOnInit() {
  }
}