【问题标题】:How to assign Angular @Input value into another variable and populate into the child?如何将 Angular @Input 值分配给另一个变量并填充到子变量中?
【发布时间】:2019-10-21 06:28:40
【问题描述】:

我有以下父 html

<p>Parent</p>
<app-child [mainData]="mainData"></app-child>

父.ts

mainData = [];
ngOnInit() { 
 this.myService((res)=>{
 this.mainData = res;
})
}

子 html

<p>My JSON {{mainData | json}}</p> //Here getting result from parent

child.ts

@Input() mainData = [];
myDataCopy = [];
ngOnInit() { 
   this.myDataCopy = this.mainData; 
   console.log('My copy Data', this.myDataCopy); // Doesn't get result on here 
}

如果我需要处理@Input 数据怎么可能?

【问题讨论】:

  • 能分享一下myService()的实现吗?回调表明你在这里使用了一些异步,这可以解释为什么你的代码不能按照你想要的方式工作

标签: angular


【解决方案1】:

ngOnChanges 生命周期挂钩中尝试

child.ts

ngOnChanges(changes: SimpleChanges) {
  const mainDataChange = changes.mainData ;

  if (mainDataChange) {
    this.myDataCopy = this.mainData; 
    // or, this.myDataCopy = mainDataChange.currentValue;
    console.log('My copy Data', this.myDataCopy);
  }
}

【讨论】:

  • 你的意思是 SimpleChanges?
  • SimpleChange 类表示从先前值到新值的基本更改。
【解决方案2】:

你可以试试@Input getter 和 setter

  _mainData: any;
  @Input()
  set mainData( val ) {
    this._mainData = val;
  }

  get mainData: any {
    return this._mainData;
  }

阅读更多Here

【讨论】:

    【解决方案3】:

    也许语法取决于 Angular 版本...

    您可以尝试在@Input 声明中强制“bindingPropertyName”参数吗?

    喜欢:

    @Input('mainData') mainData = [];

    【讨论】:

      【解决方案4】:

      只是为了抛出另一个取自this blog的替代方案。

      Stackblitz

      export class ChildComponent implements OnChanges  {
        /* METHOD THREE 
         * Using a decorator
        */
        @OnChange<number>((value, simpleChange) => {
          console.log('OnChange decorator methodThree', value)
        })
        @Input()
        methodThree: number;
      
      }
      

      装饰器

      export interface SimpleChange<T> {
        firstChange: boolean;
        previousValue: T;
        currentValue: T;
        isFirstChange: () => boolean;
      }
      
      export function OnChange<T = any>(callback: (value: T, simpleChange?: SimpleChange<T>) => void) {
        const cachedValueKey = Symbol();
        const isFirstChangeKey = Symbol();
        return (target: any, key: PropertyKey) => {
          Object.defineProperty(target, key, {
            set: function (value) {
              // change status of "isFirstChange"
              if (this[isFirstChangeKey] === undefined) {
                this[isFirstChangeKey] = true;
              } else {
                this[isFirstChangeKey] = false;
              }
              // No operation if new value is same as old value
              if (!this[isFirstChangeKey] && this[cachedValueKey] === value) {
                return;
              }
              const oldValue = this[cachedValueKey];
              this[cachedValueKey] = value;
              const simpleChange: SimpleChange<T> = {
                firstChange: this[isFirstChangeKey],
                previousValue: oldValue,
                currentValue: this[cachedValueKey],
                isFirstChange: () => this[isFirstChangeKey],
              };
              callback.call(this, this[cachedValueKey], simpleChange);
            },
            get: function () {
              return this[cachedValueKey];
            },
          });
        };
      }
      

      此方法使用typescript decorator。恕我直言,装饰者可能会留下,但...

      装饰器是一项实验性功能,可能会在未来的版本中发生变化

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-09
        • 1970-01-01
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        相关资源
        最近更新 更多