2017-08-29 77 views
1

我有一個組件具有顯示數據庫行的表。這個組件也有一個「添加」按鈕。如何在模式組件關閉後刷新父組件

當我點擊這個按鈕時,一個模式會出現一個窗體,在數據庫中添加一個新條目。

我可以將行保存到數據庫,但我想刷新父組件中的表以顯示新添加的條目。

我使用的代碼是:

<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']);這是父組件的路線什麼都不做。我如何去父組件並刷新它?

+1

最佳做法是爲表格動態生成DOM,並簡單地更新父組件的變量以包含新項目。這實際上是一個非常廣泛的組件交互問題,並且有幾種方法可以實現它。總的想法是,您需要您的父組件監視某個事件,並讓createagentieService或childcomponent發出一個事件讓它知道要更新。 –

+0

我是Angular發展的新手。你能舉一個例子說明如何實現這個目標嗎? –

回答

1

我會打開父組件的模態,並傳遞一個子組件的函數,這是在創建完成後傳遞新項目的模塊,然後將其添加到您的項目列表中。我要給一個ng-bootstrap引導的例子。

在爲父級TS:

itemList : Item[] = []; 

itemCreated(item: Item){ 
    itemList.push(item); 
} 

在爲父級HTML:

<button type="button" (click)="modal.showModal();">Add Item</button> 
<item-creator #modal (itemCreated)="itemCreated($event)"></item-creator> 

在ItemCreator組件的TS:

@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 
    } 
} 

的ItemCreate HTML中AA NG-自舉模式:

<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>