angular6 监听组件属性变化

文章目录

    • 文章参考
    • 问题描述
    • 解决办法——ngOnChanges
    • 官方例子
    • 自己写的简单例子

文章参考

  1. 官方文档解释监听数据变化
  2. angular4,angular6 父组件异步获取数据传值子组件 undefined 问题

问题描述

  1. 异步获取数据,然后将数据传递给子组件,此时子组件已经初始化完成,但是子组件如何获取新的数据,然后重新渲染

解决办法——ngOnChanges

父组件在初始化或者在修改子组件的输入属性时被调用。引用类型改变,不触发,初始化输入属性

官方例子

import {
      Component, Input, OnChanges, SimpleChange } from '@angular/core';

@Component({
     
  selector: 'app-version-child',
  template: `
    

Version { {major}}.{ {minor}}

Change log:

  • { {change}}
`
}) export class VersionChildComponent implements OnChanges { @Input() major: number; @Input() minor: number; changeLog: string[] = []; ngOnChanges(changes: { [propKey: string]: SimpleChange}) { let log: string[] = []; for (let propName in changes) { let changedProp = changes[propName]; let to = JSON.stringify(changedProp.currentValue); if (changedProp.isFirstChange()) { log.push(`Initial value of ${ propName} set to ${ to}`); } else { let from = JSON.stringify(changedProp.previousValue); log.push(`${ propName} changed from ${ from} to ${ to}`); } } this.changeLog.push(log.join(', ')); } }

自己写的简单例子

import {
      Component, OnInit,Input, SimpleChanges } from '@angular/core';
import {
     IQuersion} from '@app/types/IQuersion'

@Component({
     
  selector: 'app-single-choice',
  templateUrl: './single-choice.component.html',
  styleUrls: ['./single-choice.component.scss']
})
export class SingleChoiceComponent implements OnInit {
     
  @Input() question: IQuersion;
  questionObj: IQuersion;
  favoriteSeason: string

  constructor() {
     
  }

  ngOnInit(): void {
     
  }

  // 监听传递过来的数据,发生变化则重新赋值
  ngOnChanges(changesQuestion: SimpleChanges) {
     
    // changesQuestion.question.currentValue 为传递过来的值
    this.questionObj = changesQuestion.question.currentValue
  }

}

你可能感兴趣的:(angular6,ionic4,typescript,rx)