【问题标题】:How to refresh/reload a parent component onclick of child component submit button in angular 6?如何在 Angular 6 中刷新/重新加载父组件 onclick 子组件提交按钮?
【发布时间】:2019-01-25 17:41:29
【问题描述】:

我的父组件ts文件包含这段代码:

 openNewModal(): void {
    this.$modal.show(CategoryAddModalComponent)
        .subscribe(r => {
   });
   location.reload();
  }

我的子组件html:

    <form action="">
    <label>Enter Category</label>
        <input name="cate" type="text">
        <input name="category" type="text">
        <button class="common-btn btn-cancel" (click)="modal.hide();l>Cancel</button>
    <button class="common-btn btn" type="submit" (click)="fun_addcategory()">Submit</button>
   </form>

所以使用这个 openNewModal() 函数我调用了我的子组件模型。现在在提交我的子组件时,我需要重新加载我的父组件文件。如果我尝试在此函数中调用 location.reload,我的子组件将被重新加载。但我需要重新加载父组件。有人可以指导我如何做到这一点吗?

【问题讨论】:

  • 你重新加载父组件的目的是什么?如果你想改变 UI 状态,那么还有其他几种方法可以做到。 ` location.reload` 在您的情况下不是一个好的选择。
  • 在单页应用程序中,您无需重新加载整个应用程序或位置,而是更改组件数据,更改检测将重新呈现您的模板。如果您添加更多代码并进行更多解释,我们可能会为您提供帮助。
  • @ArpitMeena 加载父组件我正在进行 http 调用以显示一些内容。同样在子组件中添加一些内容后,进行 http 调用以将内容发布到服务器中。发布后,我需要在父组件文件中显示通过子组件发布的相同内容。现在手动刷新页面,内容正在显示。所以我需要通过一些功能重新加载它

标签: html angular angular6


【解决方案1】:

无需重新加载页面

使用 ChangeDetectorRef 手动检测父级内部的更改

示例: parent.ts

import {ChangeDetectorRef} from '@angular.core';

constructor(private cdr:ChangeDetectorRef){}

ngOnInit(){
this.service.susbscribe((data)=>{
 this.data=data;
//detect the change manually using 
this.cdr.detectChanges();
//Checks this view and its children. 
local change detection checks

})}

【讨论】:

  • 感谢您的回复。你能解释一下这段代码吗? @切拉潘
  • changeDetecorRef 是用于检测 Angular 应用程序变化的服务。在你的父组件构造器中注入 changeDetectorRef 然后使用 detectChanges() 方法在你想要检测变化的地方手动检测变化
  • 我收到此错误:错误 TS2339:“ParentComponent”类型上不存在属性“服务”。
  • 错误 TS2339:“ParentComponent”类型上不存在属性“服务”。
  • 我举了一个例子,你需要使用你的服务调用方法
【解决方案2】:

您需要传递一个附加标志来跳过这样的位置更改 ''' this.router.navigate(['parentComponent', id, type], {skipLocationChange: true}); '''

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多