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 –
父組件是估計明細組件,並應顯示聯繫人組件中的選定聯繫人。 –