在Angular 2中设置同级实例组件的属性

最后发布: 2017-12-06 18:56:24


问题

这是有关组件之间关系的基本Angular问题,尽管到目前为止我还不明白。 我有一个孩子和一个父母组成部分。 我想显示子组件的所有实例,除非单击了其中一个子组件(以防万一,请隐藏其他所有内容)。

这是子组件:

import { Component, OnInit, Input, SimpleChanges, ViewChild, ElementRef, EventEmitter, Output } from '@angular/core';
import { Customer } from './customer.model';
declare var $: any;

@Component({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.css']
})
export class CustomerDetailComponent implements OnInit {
  @Input('customer') customer : Customer;
  @ViewChild('wrapperDiv') wrapperDiv: ElementRef;
  @Output() selected = new EventEmitter<CustomerDetailComponent>();

  constructor() {
  }

  ngOnInit() {

  }

  customerFormOnClick(){
    this.selected.emit(this);
  }

}

这是父HTML:

<div *ngIf="!initialized" class="loading">Loading&#8230;</div>
<app-customer-detail *ngFor="let c of customers" (selected)="onCustomerSelected($event)" [customer]="c"></app-customer-detail>

这是父组件:

import { Component, OnInit, Input, Output } from '@angular/core';
import { Customer } from '../customer-list/customer-detail/customer.model';
import { WebApiObservableService } from '../shared/web-api.service';
import * as GLOBALS from '../globals';
import { environment } from '../../environments/environment';
declare var $: any;

@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
  initialized: boolean = false;
  customers: Customer[] = [];

  @Input('selectedCustomer') selectedCustomer : Customer;
  url = environment.titlesUrl;
  body = environment.titlesBody;

  constructor(private customersWebService : WebApiObservableService) {
  }

  ngOnInit() {
    this.customersWebService.createService(this.url, this.body)
      .subscribe(
        result => {
          this.initialized = true;
          this.customers = [];
          result.titles.forEach(element => {
            var customer = new Customer(element.mainloanerdetails, element.iconflag, element.shortname);
            this.customers.push(customer);
          });
        },
        error => {
          console.log(error)
        }
      )
  }

  ngOnChanges(){

  }

  onCustomerSelected($event){
    var count = 0
    this.customers.forEach(element => {
      if (element != $event.customer){
        // NOW, HERE I HAVE THE CHILD COMPONENET, BUT I DON'T WANT TO fadeOut() IT, I WANT TO fadeOut() THE ELEMENT (BUT THE ELEMENT IS A CUSTOMER, NOT AN ELEMENTREF
        //$($event.wrapperDiv.nativeElement).fadeOut()
      }
    });
  }

}

谢谢!

angular