【Angular07】组件间通信

父子组件

@Input

组件: 接收来自父组件的参数

@ViewChild

@ViewChild 属性装饰器,将子组件 CountdownTimerComponent 注入到私有属性 timerComponent 里面

  • import { AfterViewInit, ViewChild } from '@angular/core';
    import { Component }                from '@angular/core';
    import { CountdownTimerComponent }  from './countdown-timer.component';
    
    @Component({
      selector: 'app-countdown-parent-vc',
      template: `
      <h3>Countdown to Liftoff (via ViewChild)</h3>
      <button (click)="start()">Start</button>
      <button (click)="stop()">Stop</button>
      <div class="seconds">{{ seconds() }}</div>
      <app-countdown-timer></app-countdown-timer>
      `,
      styleUrls: ['../assets/demo.css']
    })
    export class CountdownViewChildParentComponent implements AfterViewInit {
    
      @ViewChild(CountdownTimerComponent)
     private timerComponent: CountdownTimerComponent;
    
      seconds() { return 0; }
    
      ngAfterViewInit() {
        setTimeout(() => this.seconds = () => this.timerComponent.seconds, 0);
      }
    
      start() { this.timerComponent.start(); }
      stop() { this.timerComponent.stop(); }
    }

1

1

1

1

1

1

1

兄弟组件

11

1

1

1

1

不相关组件

11

1

1

1

1

posted @ 2020-09-17 15:29  耶梦加德  阅读(155)  评论(0编辑  收藏  举报