简体   繁体   English

子组件输入属性是否在 ngOnInit 之前解析?

[英]Are child component input properties resolved before ngOnInit?

I have a parent component that is creating three identical child components.我有一个创建三个相同子组件的父组件。 The children have an input that corresponds to some autocomplete data formatted as an array.孩子有一个输入,对应于一些格式化为数组的自动完成数据。 However when I attempt to populate the array in the parent's ngOnInit and then pass it to one of the children, the child receives undefined as the array instance.但是,当我尝试在父级的 ngOnInit 中填充数组,然后将其传递给其中一个子级时,子级接收 undefined 作为数组实例。 If I try passing null as the input the same thing happens.如果我尝试将 null 作为输入传递,则会发生同样的事情。

I'm just wondering if the lifecycle is causing this and I should use ngAfterInit or something else instead?我只是想知道生命周期是否导致了这种情况,我应该使用 ngAfterInit 还是其他什么?

Parent component父组件

<app-alert-chip-list [autocompleteData]="targetGroupAutocomplete"></app-alert-chip-list>
<app-alert-chip-list [fArray]="alertContacts" [autocompleteData]="null"></app-alert-chip-list>
...

ngOnInit() {
    this.targetGroupAutocomplete = ['This is the first autocomplete', 'This is a second sentence that is a longer sentence than the first autocomplete', 'This'];
  }

Child component子组件

@Input() fArray: FormArray;
  @Input() autocompleteData: string[];

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    if(this.autocompleteData && this.autocompleteData.length != 0) {
      this.usesAutocomplete = true;
    }
    console.log("AC:", this.autocompleteData); //Ends up printing undefined
  }

you need to watch your child inputs changes through ngOnchanges你需要通过 ngOnchanges 观察你的孩子输入的变化

ngOnChanges(changes: SimpleChanges): void {
    for (let propName in changes) {
      let change = changes[propName];
      if (propName === "YOUR_INPUT_NAME") {
        this.YOUR_INPUT_NAME = (change.currentValue);
          // you can add whatever logic that to be executed. depend on which input is changed 
      }
    }
  }

I suggest another approach: use "setters" in your input:我建议另一种方法:在您的输入中使用“setter”:

private _autoCompleteData: string[]; //declare a a private variable

@Input() fArray: FormArray;

@Input() set autocompleteData(value) {
  this._autoCompleteData = value; //equal the variable

  if(value && value.length != 0) { //another code that it's relationated with autoCompleteData
    this.usesAutocomplete = true;
    console.log("AC:", this.autocompleteData); //Ends up printing undefined
  }
}

get autoCompleteData() {
  return this._autoCompleteData
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM