Angular-将组件从其他组件刷新:将子组件转换为父组件,然后将父组件传递给另一个子组件 [英] Angular - Refresh component from other component : child to parent then parent to another child communication

查看:34
本文介绍了Angular-将组件从其他组件刷新:将子组件转换为父组件,然后将父组件传递给另一个子组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 @Output 装饰器从另一个组件刷新组件?

how can i refresh component from another component using @Output decorator?

就我而言,我需要在(click)="uploadMenu()

in my case, i need to refresh component C from component B => on (click)="uploadMenu()

<代码>上级:成分A子1:成分B子2:成分C

组件A (父级) html

<div class="row">
      <div class="col-6">
        <app-uploadmenus></app-uploadmenus>
      </div>
</div>

<div class="row">
      <div class="col-6">
        <app-listemenus></app-listemenus>
      </div>
</div>

组件B (子级) html

<button class="btn btn-success" (click)="uploadMenu()">

组件B (子级) TS < ==操作

Component B (child) TS<== action

uploadMenu() {

  this.appService.insertMenuSql(this.downloadurl, this.filename).subscribe((data) => {

      this.message = data["msessage"];

      //action here

    }, error => console.log(error));
  }

组件C (子级) TS < ==刷新目标

Component C (child) TS<== target to refresh

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

//???

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

  constructor() { }

  ngOnInit() {
  }


}

推荐答案

在子B中使用 EventEmitter 执行父A中的函数,然后在父A中使用 ViewChild 在A中执行子C中的功能.

Use an EventEmitter in child B to execute a function in parent A, which then uses a ViewChild in A, to execute a function in child C.

容易.

组件A应该如下所示:

<div class="row">
  <div class="col-6">
    <app-uploadmenus (messageEvent)="uploadMenuPressed($event)"></app-uploadmenus>
  </div>
</div>

<div class="row">
  <div class="col-6">
    <app-listemenus></app-listemenus>
  </div>
</div>

组件B需要这三件事:

import { Output, EventEmitter } from '@angular/core';
@Output() messageEvent = new EventEmitter<string>();

buttonPressed() {
  this.messageEvent.emit('done');
}

组件C需要:

refreshMenu() {
  //do something here
}

最后,组件A需要一个视图子级和一个函数来接受发出调用

finally component A needs a view child and a function to accept the emit call

import { ViewChild } from '@angular/core';
import { CComponent } from ...
@ViewChild(CComponent) cComponent: CComponent;

uploadMenuPressed(event:string) {
  this.cComponent.refreshMenu();
}

应该这样做.祝你好运!

that should do it. good luck!

这篇关于Angular-将组件从其他组件刷新:将子组件转换为父组件,然后将父组件传递给另一个子组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆