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 { }
  • 相关阅读:
    Hibernate:组合模式解决树的映射
    以面到点的学习MFC
    linux内核--进程与线程
    控件自定义
    火车车次查询-余票查询--Api接口
    如何处理大量数据并发操作(数据库锁机制详解)
    Java单链表、双端链表、有序链表实现
    事务、数据库事务、事务隔离级别、锁的简单总结
    数据库连接池分析
    Spring面试题集
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314489.html
Copyright © 2011-2022 走看看