首页 > 解决方案 > 如何将一个组件中的变量用于角度的另一个组件

问题描述

在角度应用程序中,我必须使用一个变量,该变量是在一个组件到另一个组件的函数中定义的

仪表板.component.ts


export class DashboardComponent implements OnInit {
public nnum: string;
  public ncount: number = 0;

// some code

  addNotification(msg) {
    //const nl = document.querySelector("#notify");
    const nlnum = document.querySelector("#notificount");
    var el = document.createElement("li");
    if (msg.event == "New Signal") {
      if (wifiarray.indexOf(msg.mac) !== -1) {
        console.log("Already exists");
      } else {
        lcount = lcount + 1;
        this.ncount = lcount;

导航组件.ts

import { Component, OnInit } from '@angular/core';
import { NotifyService } from '../../notify.service';


export class NavbarComponent implements OnInit {


}

导航组件.html



      <li class="nav-item dropdown" ngbDropdown>
        <a class="nav-link count-indicator dropdown-toggle" id="notificationDropdown" ngbDropdownToggle>
          
          <i class="fa fa-bell">
 
</i>

<span class="badge badge-pill badge-danger badge-up" >{{ncount}}</span>

        </a>
</li>

我有通知服务 notify.service

import { Injectable } from "@angular/core";
export interface Message {
 
}

现在我想使用从仪表板组件到导航栏组件的 ncount 值来查看该值。

我已经尝试但没有工作,任何人都可以帮助我解决这个问题。

标签: angulartypescriptobservableangular8

解决方案


Angular 提供了InputOutput装饰器父组件和子组件传递数据。请找到参考链接

如果DashboardComponentNavComponent的子组件,并且您想将一些可变数据传递给其父组件,则必须将Output装饰器与EventEmitter结合使用,在DashboardComponent类中声明。您将声明如下内容:

@Output() myCount = new EventEmitter<number>();

现在,无论您的变量值发生什么变化,都可以通过这个输出装饰器发出相同的值。像这样的东西:

this.ncount = lcount; //from your sample code
this.myCount.emit(ncount);

现在在声明DashboardComponent的父组件中,您必须声明此输出发射器属性,如下所示:

<dashboard (myCount)="countChange($event)"></dashboard>

您将在这样的countChange事件中收到更新的ncount值。(请注意,您应该必须在 NavComponent.ts 中声明countChange

public countChange(newCount: number)
{
  console.log(newCount);
}

推荐阅读