文章内容

2020/6/11 11:10:42,作 者: 黄兵

Angular 子组件向父组件传值

再Angular经常用到父组件向子组件传值,但是今天需要用到子组件向父组件传值。

具体子组件代码如下:

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

export class PanelComponent {
  private count: number;
  //准备用它来发射事件
  @Output() NotificationCount = new EventEmitter();
  
  getAlertMessage() {
    this.sub = this._alertService.getAlert().subscribe((res: any) => {
      this.notArchive = res.not_archive;
      this.archive = res.archive;
      this.count = this.archive.length + this.notArchive.length;
      this.NotificationCount.emit(this.count);
    }, (error: any) => {
      console.log(error);
    });
  }

之后再父组件页面代码如下:

<button class="header-alert-button mat-button-override mat-button md-ink-ripple mat-elevation-z0"
mat-raised-button
[matMenuTriggerFor]="notificationMenu"
matTooltip="notification"
aria-label="alert">
<mat-icon aria-label="alert" matBadge="{{count|number}}" matBadgeColor="accent">add_alert</mat-icon>
<!-- <mat-icon aria-label="alert" matBadge="15" matBadgeColor="accent" matBadgeHidden="true">add_alert</mat-icon>-->
</button>
<mat-menu #notificationMenu="matMenu" class="mat-menu-panel-override" xPosition="before">
<app-notification-panel (NotificationCount)="checkChange($event)"></app-notification-panel>
</mat-menu>

这里NotificationCount绑定了事件,具体代码如下:

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

@Component({
  selector: 'app-alert',
  templateUrl: './alert.component.html',
  styleUrls: ['./alert.component.scss'],
  encapsulation: ViewEncapsulation.None,
})

export class AlertComponent implements OnInit {
  count: number;

  ngOnInit() {

  }

  checkChange($event) {
    this.count = $event;
  }
}

之后父组件绑定count值,完成了从子组件向父组件传值的工作。


参考资料:

1、Angular4子组件向父组件传值


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - Angular 子组件向父组件传值

分享到:

发表评论

评论列表