我需要从组件中的对象数组中选择一个对象,并将该值显示在不同的组件中。目前,我可以选择对象并通过{{}}将其显示在同一个组件中,但我无法让所选对象出现在其他组件中。
估计-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>
答案 0 :(得分:1)
在从孩子到父母的沟通中,您需要使用Output()
在您的孩子中,声明向父母发送事件的Output
:
@Output() selected = new EventEmitter<string>();
在您的模板中,使用click事件触发了onSelect
函数。它应该是这样的:
onSelect(contact) {
this.selected.emit(contact)
}
在您的父母看事件:
<my-Contacts (selected)=($event)></my-Contacts>
selected(contact) {
this.selectedContact = contact;
}
就是这样,现在您在selectedContact
变量中拥有所选联系人。 :)这是一个示例plunker和更详细的儿童对父母沟通的描述,即使用Output
更详细地解释here。