angular - 如何将一个组件中的变量用于角度的另一个组件
问题描述
在角度应用程序中,我必须使用一个变量,该变量是在一个组件到另一个组件的函数中定义的
仪表板.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 值来查看该值。
我已经尝试但没有工作,任何人都可以帮助我解决这个问题。
解决方案
Angular 提供了Input和Output装饰器来向父组件和子组件传递数据。请找到参考链接。
如果DashboardComponent是NavComponent的子组件,并且您想将一些可变数据传递给其父组件,则必须将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);
}
推荐阅读
- sql-server - 无法在引用同一表的同一列的表的两列上添加更新级联
- pandas - 对时间数据列pandas python执行mod函数
- node.js - 如何在开始日期和结束日期之间运行这个 mongo 查询
- c - 如何在 C 中将 8 字节整数除以四个 2 字节十六进制?
- discord - 使用 discord.js v12 狙击多个旧消息
- kubernetes - kubectl:如何获取更详细的日志?
- phpstorm - 提交时自动更改代码,使用 PhpStorm IDE
- python - Python 强制转换导致奇怪的可变性结果
- c++ - 派生类的接口和数据成员
- python - 如何使用python解析json数据?