我有一个带有表的组件,用于显示数据库中的行。该组件还有一个“添加”按钮。
当我点击此按钮时,会出现一个模式,其中包含一个表单,用于在数据库中添加新条目。
我可以将行保存到数据库,但我想刷新父组件中的表以显示新添加的条目。
我使用的代码是:
在父组件中的我打开模态:
<div>
<a href="#responsive-modal" data-toggle="modal" data-target="#responsive-modal" class="btn btn-md btn-add animated flipInX flipInY lightSpeedIn slideInUp" (click)="createAgentie(agentie2)"><i class="fa fa-plus"></i> Add</a>
<createagentie></createagentie>
</div>
TS:
@ViewChild(CreateAgentieComponent) createAgentie: any = {};
CreateAgentiee(agentie2: any = {}) {
this.createAgentie.myObject = agentie2;
this.createAgentie.open();
}
子组件中的:
<button type="button" (click)="submit()" class="btn btn-danger waves-effect waves-light" data-dismiss="modal">Save changes</button>
TS:
submit() {
this.createagentieService.create(this.myObject)
.subscribe(x => {
console.log(x);
this.myObject.denumire = "";
this.router.navigate(['/vizualizareagentii']);
});
}
问题是this.router.navigate(['/ vizualizareagentii']);哪个是父组件的路由什么都不做。如何进入父组件并刷新它?
答案 0 :(得分:3)
我会在父组件上打开模态并传入子组件的函数,子组件是在创建发生后传回新项的模式,然后将其添加到Items列表中。我将给出一个ng-bootstrap引导的例子。
在ParentComponent ts:
<button type="button" (click)="modal.showModal();">Add Item</button>
<item-creator #modal (itemCreated)="itemCreated($event)"></item-creator>
在ParentComponent html中:
@Output() itemCreated= new EventEmitter<Item>();
@ViewChild('itemCreateMdl') itemCreateMdl: ElementRef;
item : Item = new Item(); //make the form build out this item
constructor(private myService : Service, private modalService: NgbModal){}
showModal(){
this.modalService.open(this.itemCreateMdl);
}
buttonPressedSaveItem(){
this.myService.createTheThing(this.item).subscribe(returnedItem => {
this.itemCreated.emit(returnedItem);//assuming you already unwrapped it from the json
}
}
在ItemCreator组件的ts:
中<ng-template #itemCreateMdl let-c="close" let-d="dismiss">
//add in the typical bootstrap modal-header and modal-body stuff
<div class="modal-footer">
<button type="button" class="btn btn-primary" (click)="buttonPressedSaveItem();c('Close click');">Add</button>
</div>
</ng-template>
ItemCreate html是一个ng-bootstrap模式:
{{1}}