1
我需要从组件中的对象数组中选择一个对象,并使该值出现在其他组件中。目前,我可以选择对象并通过{{}}将其显示在同一个组件中,但是我无法将所选对象显示在其他组件中。Angular 2 - 从一个JSON数组中选择一个对象并将其显示给另一个组件
估计-detail.component.ts
@Component({
selector: 'my-estimate-detail',
templateUrl: './app/components/estimateDetail/estimate-detail.component.html'
})
export class EstimateDetailComponent implements OnInit {
@Input() estimate: Estimate;
@Input() item: Item;
@Input() contact: Contact[];
title="Estimate Details";
counterValue = 1;
selectedContact:string;
Items:Item[];
newEstimate = false;
startDate:any;
error: any;
navigated = false; // true if navigated here
constructor(
private estimateService: EstimateService,
private itemService:ItemService,
private route: ActivatedRoute) {
this.startDate = new Date();
}
ngOnInit() {
this.getItems();
this.route.params.forEach((params: Params) => {
let id = params['id'];
if (id === 'new') {
this.newEstimate = true;
this.estimate = new Estimate();
} else {
this.newEstimate = false;
this.estimateService.getEstimate(id)
.then(estimate => this.estimate = estimate);
}
});
}
估计-detail.component.html
div *ngIf="estimate" class="form-horizontal">
<h2>{{title}}</h2>
<h3> Basic Info</h3>
<my-Contacts [(selectedContact)] = 'SelectedContact'></my-Contacts>
{{SelectedContact}}
<div>
contacts.component.ts
@Component({
selector: 'my-Contacts',
templateUrl: './app/components/Contacts/Contacts.component.html'
})
export class ContactsComponent implements OnInit {
//@Output:Contact;
title = "My Contacts";
@Input() Contacts: Contact[];
@Input() selectedContact: Contact;
@Output() onSelect: EventEmitter<Contact> = new EventEmitter();
error: any;
constructor(
private router: Router,
private contactService: ContactService) { }
getContacts() {
this.contactService.getContacts()
.then(Contacts => this.Contacts = Contacts);
}
ngOnInit() {
this.getContacts();
}
// onSelect(contact: Contact) {
// this.selectedContact = contact; }
个contacts.component.html
<div class="col-md-12">
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let contact of Contacts" [class.active]="contact === selectedContact" (click)="onSelect(contact)">
<td>{{contact.name}}</td>
<td>{{contact.address1}}</td>
<td><button class="btn btn-danger" (click)="deleteContact(contact, $event)">Delete</button></td>
</tr>
</tbody>
</table>
</div>
这个另一个组件如何与您的contacts.component相关?谁是孩子的父母成分? –
https://angular.io/docs/ts/latest/cookbook/component-communication.html –
父组件是估计明细组件,并应显示联系人组件中的选定联系人。 –