【问题标题】:How to refresh parent component after modal component closes模态组件关闭后如何刷新父组件
【发布时间】:2018-02-07 03:02:10
【问题描述】:

我有一个带有表格的组件,该表格显示数据库中的行。该组件还有一个“添加”按钮。

当我单击此按钮时,会出现一个带有表单的模式,用于在数据库中添加新条目。

我可以将行保存到数据库中,但我想刷新父组件中的表以显示新添加的条目。

我使用的代码是:

在父组件中,我打开模式:

<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']);这是父组件的路由什么都不做。怎么去父组件刷新一下?

【问题讨论】:

  • 最佳实践是为表格动态生成 DOM,并简单地更新父组件的变量以包含新项目。这实际上是一个非常广泛的组件交互问题,并且有几种方法可以实现。一般的想法是您需要您的父组件来监视事件,并让 createagentieService 或子组件发出事件以使其知道更新。
  • 我是 Angular 开发的新手。您能否举例说明如何实现这一目标?

标签: angular


【解决方案1】:

我将在父组件上打开模态并为子组件传递一个函数,该函数是在创建发生后将新项目传回的模态,然后将其添加到您的项目列表中。我将给出一个 ng-bootstrap 引导示例。

在ParentComponent ts中:

itemList : Item[] = [];

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

在 ParentComponent 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 是一个 ng-bootstrap 模式:

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

【讨论】:

  • 感谢您的回复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 2019-11-15
  • 1970-01-01
相关资源
最近更新 更多