简体   繁体   English

Angular 10 - 事件发射器不起作用 - 在子组件和父组件之间共享信息

[英]Angular 10 - Event Emmiter is not working - Sharing information between child and parent component

I've this parent-child components in Angular and I'm trying to pass an object from the child component to the parent in order to update a value from the parent's object array.我在 Angular 中有这个父子组件,我试图将一个对象从子组件传递给父组件,以便更新父对象数组中的值。 I've been followint the angular documentation example but seems like it's not sending the new object to the paren component but it's not showing any error neither the console or the VSC terminal.我一直在关注 angular 文档示例,但似乎它没有将新对象发送到 paren 组件,但它没有显示任何错误,无论是控制台还是 VSC 终端。

This is the angular guide I followed: https://angular.io/guide/inputs-outputs#sending-data-to-a-parent-component这是我遵循的角度指南: https : //angular.io/guide/inputs-outputs#sending-data-to-a-parent-component

Parent view:父视图:

<h1>Customers list</h1>

<mat-list>
  <a mat-list-item *ngFor="let customr of customers" [routerLink]="[customr.id, {name: customr.name}]">{{ customr.name }}</a>
</mat-list>


<router-outlet (newItemEvent)="addItem($event)"></router-outlet>

Parent controller:

import { Component, OnInit, Output } from '@angular/core';

@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.scss']
})
export class CustomerListComponent implements OnInit {


  // list = [
  //   { id: 1, name: 'John Smith' },
  //   { id: 2, name: 'Anna Highland' },
  //   { id: 3, name: 'Emilie Poiret' }
  // ];

  customers: Array<Object> = [
    {
      id: 1,
      name: 'John Smith'
    },
    {
      id: 2,
      name: 'Anna Highland'
    },
    {
      id: 3,
      name: 'Emilie Poiret'
    }
  ];

  addItem(customer){
    console.log(`add customer ${customer}`);
  }

  constructor() { }

  updateCustomer(data){
    console.log(data);
  }

  ngOnInit(): void {
  }
}

Child view:子视图:

<p>{{ name }}</p>


<form [formGroup]="formGroup" (ngSubmit)='addNewItem()'>

  <mat-form-field>
    <mat-label>Customer name:</mat-label>
    <input matInput name="customerName" formControlName="customerName">
  </mat-form-field>

  <button mat-raised-button type="submit">Action</button>

</form>

Child controller:子控制器:

import { ActivatedRoute, Params } from '@angular/router';
import { Component, Input, OnInit } from '@angular/core';
import { AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-customer-detail',
  templateUrl: './customer-detail.component.html',
  styleUrls: ['./customer-detail.component.scss']
})
export class CustomerDetailComponent implements OnInit {

  // https://angular.io/guide/inputs-outputs#sending-data-to-a-parent-component
  @Output() newItemEvent = new EventEmitter<object>();

  formGroup: FormGroup;
  id: string;
  name: string;

  addNewItem(){
  //  console.log(`emit runs ${value}`);
    let id: any = this.id;
    let name = this.formGroup.value.customerName;
    console.log(`id: ${this.id} i name: ${this.formGroup.value.customerName}`);
    let customer = {
      'id': this.id,
      'name': this.formGroup.value.customerName
    };
    console.warn(customer);
    this.newItemEvent.emit(customer);
  }


  constructor(private fb: FormBuilder, private routes: ActivatedRoute) { }

  ngOnInit(): void {

    this.routes.params.subscribe(
      (params: Params) => {
        this.id = params.id;
        this.name = params.name;
      }
    );

    console.log(`ngOnInit ${this.name}`);

    this.buildForm();

  }

  private buildForm(): void {
    console.log(`buildForm ${this.name}`);
    this.formGroup = this.fb.group({
      customerName: [this.name, Validators.required]
    });

  }

  public saveEdit() {
    console.log(`Save edit`);
    return { 'id': this.formGroup.value.customerId, 'name': this.formGroup.value.customerName };
  }

}

When I click on the button I se the console.log that the addNewItem it's executing but on the addItem on the parent component function I don't see the console.log, the goal is to pass the id and customer's name so I can update the customers array with the customer's new information当我点击按钮时,我看到了它正在执行的 addNewItem 的 console.log 但在父组件函数上的 addItem 上我没有看到 console.log,目标是传递 id 和客户的姓名,以便我可以更新客户数组与客户的新信息

The router outlet component is just a marker that is used by the angular router in order to know where to place the components being rendered for the different routes.路由器出口组件只是一个标记,角路由器使用它来知道在哪里放置为不同路由渲染的组件。 Placing an event listener on this component will result in nothing since it's not the actual route component.在这个组件上放置一个事件监听器不会产生任何结果,因为它不是实际的路由组件。

You could use a service or do something like this:您可以使用service或执行以下操作:

export class AppComponent {
  @ViewChild(RouterOutlet) outlet: RouterOutlet;

  constructor(router: Router) {
    router.events.pipe(filter(e => e instanceof NavigationEnd)).subscribe(() => {
      const c = this.outlet.component;
    });
  }
}
  1. Query the router outlet component查询路由器插座组件

  2. Listen for the navigation end event in order to get notified whenever the component for the route has changed.侦听导航结束事件,以便在路由组件发生更改时收到通知。

  3. Get the current component instance and do something on it.获取当前组件实例并对其进行处理。 In your case you will have an event emitter and you can subscribe for the event.在您的情况下,您将拥有一个事件发射器,您可以订阅该事件。

Here I'm assuming that this will be used in the AppComponent and I haven't unsubscribed but if you attend to use it in an inner component where you have a named outlet and the component might get destroyed at some time, make sure that you unsubscribe from the stream in order to prevent memory leaks.在这里,我假设这将在 AppComponent 中使用并且我还没有取消订阅,但是如果您打算在具有命名插座的内部组件中使用它并且该组件可能会在某个时间被破坏,请确保您取消订阅流以防止内存泄漏。

THe main reason why this is not working it's becasuse as @user1 mentioned the <router-outlet> can not receive parameters like a component would do.这不起作用的主要原因是因为@user1 提到<router-outlet>无法像组件那样接收参数。 Also, his proposal about creating a service to share all the information between components it's the most appropiate and the recomended by the Angular documentation: https://angular.io/tutorial/toh-pt4此外,他关于创建服务以在组件之间共享所有信息的建议是最合适的,也是 Angular 文档推荐的: https : //angular.io/tutorial/toh-pt4

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angular 子事件指向错误的父组件 - Angular child event targets wrong parent component 在反应中的 2 个组件之间共享数据。 无亲子关系 - sharing data between 2 component in react. no parent child relation 父组件和其他父子组件之间的Angular 5 routerLink - Angular 5 routerLink between parent component and other parent - child component 角度1-在父子控制器之间共享数据-需要建议 - Angular 1 - Sharing data between parent and child controller - Need advice 父组件中的触发事件来自路由Angular中子组件的加载 - Trigger event in Parent component from child component load in routing Angular 将事件从子组件传递到父组件 Angular 5 - Pass Event from child component to parent component Angular 5 Angular Parent / Children单击事件:在父组件中的其他子项上单击事件后,在父项中显示子组件? - Angular Parent/Children click events: Show child component in parent after click event on a different child in parent component? 带有数据服务的组件之间的数据共享在角度5中不起作用 - Data sharing between component with data servive not working in angular 5 将事件向下传递到不是Angular 2应用程序中另一个组件的父级或子级的组件 - Passing event down to a component that is not a parent or child of the other in Angular 2 app 如何在ngSwitch的Angular 2+中将事件从子级绑定到父级组件 - How to bind event from child to parent component in Angular 2+ in ngSwitch
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM