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 { }
  • 相关阅读:
    前端十万个为什么(之一):我们为什么需要npm?
    初识模块化开发工具:
    javascript 中的 let 作用域
    把汉字转换为html实体编码
    【小程序】开发过程问题整理
    【入门】正则表达式
    【CSS】面试知识整理
    【入门】Gulp 简单使用
    【入门】WebSocket 示例
    【JQ】$.ajax() 参数
  • 原文地址:https://www.cnblogs.com/estherSH/p/14314489.html
Copyright © 2011-2022 走看看