這是存在List和Form以創建新項目的常見模式。該表單顯示在引導模式中,並使用服務將該項目發送到後端。如果確定或錯誤消息,服務會迴應該項目。這個想法是通知List組件添加它。表單使用新項目發出事件,但父項方法從不被調用。Angular 2.1.0父組件未捕獲從子組件發出的事件
列表
@Component({
selector: 'app-item-list',
template: `<div class="row">
<div class="col-sm-4">
<button type="button" (click)="createItem()">Create Item</button>
</div>
</div>
<!-- Static modal -->
<app-item-form></app-item-form>
<div class="row" (itemSaved)="addItem($event)">
<div *ngFor="let item of items>
<div class="col-md-4 card-box">
<app-item [item]="item"></app-item>
</div>
</div>`
})
export class ItemListComponent {
items: Item[];
constructor(
private router: Router,
private itemService: ItemService) {
}
@ViewChild(ItemFormComponent) private itemFormComponent;
createItem() {
this.itemFormComponent.open();
}
// This should be called!
addItem(event:any) {
event.stopPropagation();
if(event.item != undefined) {
this.items.push(event.item);
}
}
}
表
@Component({
selector: 'app-item-form',
template: `<div bsModal #childModal="bs-modal" class="modal fade" tabindex="-1" role="dialog" [config]="{backdrop: 'static'}"
tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" aria-label="Close" (click)="childModal.hide()">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">{{ modalTitle }}</h4>
</div>
<div class="modal-body">
<form *ngIf="item" class="form-horizontal" role="form">
<div class="row">
<div class="form-group col-xs-12">
<input [(ngModel)]="item.title" type="text" placeholder="Item title" name="title" class="form-control"/>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" (click)="childModal.hide()">Close</button>
<button type="button" class="btn btn-primary" (click)="save(); childModal.hide()">Save changes</button>
</div>
</div>
</div>
</div>
`
})
export class ItemFormComponent {
item: Item = new Item();
@Output() itemSaved = new EventEmitter<Item>();
modalTitle = 'New Item';
constructor(
private itemService: ItemService,
private route: ActivatedRoute) {
}
save() {
this.ItemService
.save(this.item)
.then(it => {
this.item = new Item();
this.itemSaved.emit(it);
})
.catch(error => {});
}
@ViewChild('childModal') public childModal:ModalDirective;
open() {
this.childModal.show();
}
}