在Angular 2中设置兄弟实例组件的属性

时间:2017-12-06 18:56:25

标签: angular

这是关于组件之间关系的基本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()
      }
    });
  }

}

谢谢!

0 个答案:

没有答案