angular note

///

1,

父组件===> 子组件

子组件

@input 

get  {}

set  {}  的意义是希望子组件收到参数进行一些处理后,再展示;

2,子组件监听父组件值变化

// 子组件实现ngOnchanges实现监听父组件传值变化
  @Input() major: number;
  @Input() minor: number;
  changeLog: string[] = [];
  
 ngOnChanges(changes: SimpleChanges) {
    const log: string[] = [];
	//获取changes的方法
    for (const propName in changes) {
      const changedProp = changes[propName];
      const to = JSON.stringify(changedProp.currentValue);
	  //isFirstChange()第一次接受父组件传值
      if (changedProp.isFirstChange()) {
        log.push(`Initial value of ${propName} set to ${to}`);
      } else {
	  //changedProp.previousValue 获取变化前的值
        const from = JSON.stringify(changedProp.previousValue);
        log.push(`${propName} changed from ${from} to ${to}`);
      }
    }
    this.changeLog.push(log.join(', '));
  }

3,父组件获取子组件

//子组件, 关键字voted  this.voted.emit(agreed)
 @Output() voted = new EventEmitter<boolean>();
  didVote = false;

  vote(agreed: boolean) {
    this.voted.emit(agreed);
    this.didVote = true;
  }

4.父组件直接访问子组件方法

//下面是父组件代码,父组件中#timer指向子组件 start,stop 方法在子组件中实现
 <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>

  

原文地址:https://www.cnblogs.com/eiguleo/p/14824009.html