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 { }
  • 相关阅读:
    JS、LUA都可以开发移动应用
    正在融资中的快速移动应用开发平台
    赶快加入快速移动应用开发吧
    重新诠释移动应用开发
    快速开发移动应用的利器
    报表实施案例:某市利用大数据助力精准扶贫项目开展
    【新手速成】菜鸟如何在三天内完成系统开发
    全新Wijmo5中文学习指南正式上线
    SpreadJS 在 Angular2 中支持绑定哪些属性?
    【报表福利大放送】100余套报表模板免费下
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314489.html
Copyright © 2011-2022 走看看