如何使用一个分量中的变量到另一个分量的角度



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

仪表板组件.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>

我有通知服务通知服务

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

}

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

我已经试过了,但没有工作。有人能帮我吗。

Angular提供输入输出装饰器,将数据父组件和子组件传递到。请找到参考链接。

如果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);
}

最新更新