在这种情况下,如何正确地将值从第二级子组件传递到父组件?

如何解决在这种情况下,如何正确地将值从第二级子组件传递到父组件?

我不太喜欢Angular和TypeScript(我来自Java),需要解决以下问题。我不知道我认为使用的解决方案是否正确,或者是否有更好的解决方案。

基本上,我有一个名为 order-manager.component 的组件,它是呈现此表的父组件:

enter image description here

此父组件包含代表单行的对象列表:

orders: any[];

并进入 ngOnInit(),使用服务检索列表。

您可以在上一个打印屏幕中看到,可以扩展表格的每一行,以显示/编辑特定对象的详细信息。

为此,我使用了一个名为 order-details 的子组件。所以基本上在我的父组件HTML中,我有这样的东西:

DETTAGLIO ORDINE

order-details 子组件本身具有2个子组件:一个用于查看模式,另一个用于编辑模式(在上一个屏幕截图)。

基本上,在我的 order-details 组件代码中,我简单地拥有:

<p-selectButton [options]="editOrderOption"
                [(ngModel)]="editOrderSelectedOption"
                (onChange)="editOrderOptionOnChange($event,orderDetail.id)"></p-selectButton>


<div *ngIf="editOrderSelectedOption=='view';then view_content else edit_content">here is ignored</div>

<ng-template #view_content>
  <app-view-order [orderDetail]="orderDetail"></app-view-order>
</ng-template>

<ng-template #edit_content>
  <app-update-order [orderDetail]="orderDetail"></app-update-order>
</ng-template>

基本上,用户通过选择按钮选择视图或编辑模式,然后在页面中呈现一个子组件。

在特定情况下,我们使用此更新顺序组件进入编辑模式

如上图所示,此更新顺序组件允许用户编辑表单,最后包含删除按钮。单击此按钮,我想从我的表中删除代表该顺序(表的这一行)的对象。

这是我的问题。代表表行的对象列表在第一个 order-manager.component 父组件中定义,而按钮在第二个 update-order 子组件中定义,是层次结构:

order-manager component
          |
          |
          |---------> order-details component
                                |
                                |
                                |----------------> update-order component

                 

为了解决这个问题,我想我可以做这样的事情:

  1. 用户单击定义在更新顺序子组件中的删除按钮。这可以通过一种方法来处理,该方法发出一个包含当前行ID(它是object字段的唯一值)的事件。

  2. 进入 order-manager 父组件,我监听此事件。收到事件后,该事件将从代表我的表的行列表的 orders 列表中删除。

您认为实现此任务是一个不错的解决方案吗?还是我错过了一些东西,还有更好的解决方案?

解决方法

发送值即可。

一个更简单的解决方案是创建一个可以跟踪用户操作的服务。 创建一个服务说OrderChangeService并将其注入order-manager componentupdate-order component

export class OrderChangeService {
  deleteIdSubject$ = new Subject<number>(); // import { Subject } from rxjs
  deleteIdAction$ = deleteIdSubject$.asObservable()
}

现在update-order component中,当用户单击以删除特定订单时,您可以在主题上调用next()函数

  deleteOrder(id: number) {
    deleteIdSubject$.next(id);
  }

现在,您可以在订单管理器组件的deleteIdAction$函数中订阅ngOnInit()

deleteIdAction$ = this.orderChangeService.deleteIdAction$ // make sure you inject service in the constructor
  ngOnInit() {
    this.deleteIdAction$.subscribe({
      next: (id) => {
        // Do Delete action for item with id
      }
    })
  }

基本思想是,可以使用服务将信息从一个组件传递到另一个组件。随着嵌套组件深度的增加,发射值可能会出现问题

最佳方法实际上是使用NgRx进行状态管理。可能有点难以使用,但会产生更好的结果。您可以看看official documentation of NgRx

,

相反,您可以创建一个数据服务来更新和通过它获取数据

import { Injectable } from '@angular/core';
import { Subject,Observable } from 'rxjs';
@Injectable()
export class MessageService {
  private siblingMsg = new Subject<string>();
  constructor() { }
  /*
   * @return {Observable<string>} : siblingMsg
   */
  public getMessage(): Observable<string> {
    return this.siblingMsg.asObservable();
  }
  /*
   * @param {string} message : siblingMsg
   */
  public updateMessage(message: string): void {
    this.siblingMsg.next(message);
  }
}

,然后从组件中,可以使用subscription设置值。

import { Component,OnInit,OnDestroy } from '@angular/core';
import { MessageService } from './message.service';
...
export class AppComponent implements OnInit{
  public messageForSibling: string;
  public subscription: Subscription;
  constructor(
    private msgservice: MessageService // inject service
  ) {}

  public ngOnDestroy(): void {
    this.subscription.unsubscribe(); // onDestroy cancels the subscribe request
  }

  public ngOnInit(): void {
    // set subscribe to message service
    this.subscription = this.messageService.getMessage().subscribe(msg => this.messageForSibling = msg);
  }
}
,

首先,您应该在子组件中创建一个输出属性。

  @Output() 
  updated = new EventEmitter<boolean>();
  
  saveButtonClicked() {
    
    //do update
    
    this.updated.emit(true); //update success
    
  }

在您的html中定义它:

<ng-template #edit_content>
  <app-update-order [orderDetail]="orderDetail" (updated)="orderUpdated($event)"></app-update-order>
</ng-template>

现在,您可以在父组件中监听更新事件了。

orderUpdated(updated:boolean){
    if(updated){
    
    }
}

您可以找到有关组件交互here

的更多信息

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-