zoukankan      html  css  js  c++  java
  • Anngular组件交互-----4.组件监听子组件的事件

    Angular组件交互包含以下几种:

    一.子组件获取父组件的内容

    1.通过输入型绑定将数据从父组件传到子组件

    2.通过Setter截听父组件值的变化

    3.通过ngOnChanges()来截听输入值性值的变化

    二.父组件获取子组件的内容

    1.父组件监听子组件的事件

    2.父组件与子组件通过本地变量互动

    3.父组件调用@viewChild()

    4.父组件和子组件通过服务来通讯

    本节主要介绍: 1.父组件监听子组件的事件

    其流程为:

    前提: 

    1.子组件定义一个事件并输出 @Output() voted = new EventEmitter<boolean>();

    2.父组件监听子组件定义的voted事件:  <app-voter (voted) = "onVoted($event)"></app-voter>

    流程为: 子组件通过click事件或者其他事件触发  ->  发布事件voted  ->  父组件监听到子组件的voted事件  ->  父组件进行相应的操作

    具体代码为:

    子组件:

    import { Component, EventEmitter, Input, Output } from '@angular/core';
    
    @Component({
      selector: 'app-voter',
      template: `
        <h4>{{name}}</h4>
        <button (click)="vote(true)"  [disabled]="didVote">Agree</button> //点击按钮触发事件,调用函数vote
        <button (click)="vote(false)" [disabled]="didVote">Disagree</button>
      `
    })
    export class VoterComponent {
      @Input()  name: string;
      @Output() voted = new EventEmitter<boolean>(); //子组件定义一个事件
      didVote = false;
    
      vote(agreed: boolean) { //vote函数接收一个boolean类型参数并且发布一个事件
        this.voted.emit(agreed);
        this.didVote = true;
      }
    }

    父组件:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-vote-taker',
      template: `
        <h2>Should mankind colonize the Universe?</h2>
        <h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
        <app-voter *ngFor="let voter of voters"
          [name]="voter"
          (voted)="onVoted($event)"> // 父组件监听子组件的voted事件并接收相应的参数
        </app-voter>
      `
    })
    export class VoteTakerComponent {
      agreed = 0;
      disagreed = 0;
      voters = ['Narco', 'Celeritas', 'Bombasto'];
    
      onVoted(agreed: boolean) { //父组件接收参数后进行处理
        agreed ? this.agreed++ : this.disagreed++;
      }
    }
  • 相关阅读:
    bootstrap-table实现分页、导出数据至excel
    Python求多个list的交集、并集、差集 & list 排序
    JS
    python 格式化输出(% VS format)
    pyqt5_实例:修改xml文件中节点值
    博客迁移
    Reverse is Multiplex, You Need PinTools.
    ISCC2018_leftleftrightright-Writeup
    如何在linux主机上运行/调试 arm/mips架构的binary
    强网杯2018
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314201.html
Copyright © 2011-2022 走看看