微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular - 等待潜在的输入变化

如何解决Angular - 等待潜在的输入变化

我有两个组件:

child一个 @input()一个 @Output()。当收到@Output的回调时,parent可能会改变@Input的值。

是否可以在发出 EventEmitter 后等待潜在的输入更改?

为了重现问题的一些代码

@Component({
    selector: 'app-child',templateUrl: './app-child.component.html'
})
export class ChildComponent {
    @input() myInput: string;
    @Output() myOutput: EventEmitter<any> = new EventEmitter();

    public doEmit() {
        this.myOutput.emit();
    }

    private doAfterEmit() {
        // Do something with myInput - expect it to use the value updated by the parent.
    }
}
@Component({
    selector: 'app-parent',templateUrl: './app-parent.component.html'
})
export class ParentComponent {
    public theInputValue: string;

    public onEmitCallback() {
        // Update theInputValue
    }
}

app-parent.component.html

<app-child [myInput]="theInputValue" (myOutput)="onEmitCallback()"></app-child>

解决方法

我认为您可以使用 getter/setter 方法或 ngOnChanges 生命周期挂钩来查找输入的任何更改。

getter/setter 方法:

_myInput: string;
get myInput(): boolean {
  // can do other stuff too
  return this._myInput;
}
@Input() set myInput(value: string) {
  this._myInput = string;
  // do your other stuff (update the input value)
}

ngOnChanges 方法:

ngOnChanges(changes: SimpleChanges) {
  // changes has other properties as well,like 
  // changes.myInput.firstChange,changes.myInput.previousValue,changes.myInput.currentValue
  if (changes.myInput.currentValue !== changes.myInput.previousValue) {
    // the value of myInput changed from previous,so do what you would like here.
  }
}

对于您的情况,我会使用 getter/setter 方法。

您可以阅读更多相关信息here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。