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 { }
原文地址:https://www.cnblogs.com/estherSH/p/14314489.html