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++;
      }
    }
  • 相关阅读:
    python全栈开发从入门到放弃之内置函数
    python全栈开发从入门到放弃之递归函数的调用
    python全栈开发从入门到放弃之字典的应用
    python全栈开发从入门到放弃之元组的内置应用
    python全栈开发从入门到放弃之装饰器函数
    [LeetCode-JAVA] Remove Duplicates from Sorted Array II
    [LeetCode-JAVA] Simplify Path
    [LeetCode-JAVA] Permutations
    tensorboard在windows系统浏览器显示空白的解决writer =tf.summary.FileWriter("logs/", sess.graph)
    Windows64位安装CPU版TensorFlow
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314201.html
Copyright © 2011-2022 走看看