zoukankan      html  css  js  c++  java
  • Anngular组件交互-----5.父组件与子组件通过本地变量互动

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

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

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

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

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

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

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

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

    3.父组件调用@viewChild()

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

    本节主要介绍: 2.父组件与子组件通过本地变量互动

    父组件使用方式: <app-child #timer></app-child>

    用#timer代表子组件app-child, 父组件可以直接调用子组件的函数

    代码如下:

    子组件:

    import { Component, OnDestroy } from '@angular/core';
    
    @Component({
      selector: 'app-countdown-timer',
      template: '<p>{{message}}</p>'
    })
    export class CountdownTimerComponent implements OnDestroy {
    
      intervalId = 0;
      message = '';
      seconds = 11;
    
      ngOnDestroy() { this.clearTimer(); }
    
      start() { this.countDown(); }
      stop()  {
        this.clearTimer();
        this.message = `Holding at T-${this.seconds} seconds`;
      }
    
      private clearTimer() { clearInterval(this.intervalId); }
    
      private countDown() {
        this.clearTimer();
        this.intervalId = window.setInterval(() => {
          this.seconds -= 1;
          if (this.seconds === 0) {
            this.message = 'Blast off!';
          } else {
            if (this.seconds < 0) { this.seconds = 10; } // reset
            this.message = `T-${this.seconds} seconds and counting`;
          }
        }, 1000);
      }
    }

    父组件:

    import { Component } from '@angular/core';
    import { CountdownTimerComponent } from './countdown-timer.component';
    
    @Component({
      selector: 'app-countdown-parent-lv',
      template: `
      <h3>Countdown to Liftoff (via local variable)</h3>
      <button (click)="timer.start()">Start</button> //调动子组件的函数
      <button (click)="timer.stop()">Stop</button>
      <div class="seconds">{{timer.seconds}}</div>
      <app-countdown-timer #timer></app-countdown-timer> //用timer代表子组件
      `,
      styleUrls: ['../assets/demo.css']
    })
    export class CountdownLocalVarParentComponent { }
  • 相关阅读:
    elasticsearch 调整参数 调参 -- 副本 分片 读写流程 -- elasticsearch配置
    对创新的理解 -- 价值共生、协同生长
    update_by_query ingest pipeline
    create index pattern Forbidden error
    apache转发规则 + nginx location 正则匹配经典案例
    拨测ip+port 告警 telnet nc
    configMap简单理解
    sidecar收集Tomcat日志-普通用户
    使用DBeaver连接pheonix
    bladex开发自己的服务不推送服务器的方法
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314489.html
Copyright © 2011-2022 走看看