【问题标题】:@Input not taking latest value after emitted from parent component@Input 从父组件发出后不取最新值
【发布时间】:2020-01-07 09:36:57
【问题描述】:

我有一个发出最新值的父组件,而在子组件中它使用@Input,其中不返回最新值。

基本上是这样开始的 在子组件中...

@Input() test;any;

我们确实将此测试绑定到 HTML 中,然后在按钮的单击事件中我们使用输入值 'test' 执行一些操作

onClickButton() {

this.test='your request is in progress'
....does some function where in it passes call to parent componentt and there it retrives the latest data of test so I am expecting that this.test would replaced by latest data from parent component.

}

但是,这里不是这种情况,它保留了“您的请求正在进行中......”

我在 ngOnChanges(changes:simpleChanges) 之类的子组件中进行了尝试,并尝试将 currentValue 分配给 this.test 值;但事情并没有朝着正确的方向发展。即使在父组件中,一切都正确处理我尝试打印最新值,但在子组件中它仍然是旧值。

我也试过了

this.ref.detectChanges();
this.ref.markforCheck();

但事情并没有帮助我从父组件获取更新值。

父母.ts

this.test ="从服务中获取价值,并且可以在调试器中看到该价值即将到来"

【问题讨论】:

  • 给出你使用子组件的父模板文件结构..
  • @Input() 仅在输入属性的引用发生更改时检查更改。如果您只是更改值,则对象的引用是相同的,因此 onChanges 无法正常工作..this.obj = { ...this.obj } 这种解构语法您也更改了值和引用..现在 onChanges() 将被解雇..
  • 请在主线程中查看更新。
  • 在我的父组件中 this.test="last value from services" ,我在调试器本身中对此进行了验证。
  • 即使当我将鼠标悬停在更改对象上时,我也可以看到 currentValue 是我期望的最新值,但是当我单击按钮时它打印值时 this.test="your request is in progress" ,我还是不明白这里出了什么问题。

标签: angular


【解决方案1】:

我们需要查看您的父组件。

使用您当前的代码,我们看不到您将 test 变量覆盖到父组件中的那一刻。

我做了一个 StackBlitz just here,这是你需要的吗?

随意编辑并发回。

【讨论】:

    【解决方案2】:

    查看StackBlitz link

    你的 parent.html 的 html...

    <button (click)="changeValue()">Change</button>
     <hr>
    <app-child [test] ="test"></app-child>
    

    你的 .ts 的 parent.ts...

    export class AppComponent  {
       test:any ={};
       changeValue(){
           this.test['data'] = 'loading data form server...'
           setTimeout(()=>{
               this.test['data'] = "Loaded..."
           },500)
       }
    }
    

    您的 child.html 是...

    {{value |json}}
    

    你的 child.ts 是...

    export class ChildComponent implements OnInit {
       value:any;
       @Input('test') set testInput(value : any){
         this.value = value;
       }  
       constructor() { }
       ngOnInit() {
       } 
    }
    

    【讨论】:

    • 感谢 Gaurang,当我调试我的代码 [ngOnChanges] 时,它在 currentValue 中给出了正确的值,但它会将旧值打印到 html。
    • @user5769212 欢迎您,如果回答对您有帮助,可以点赞并接受它..
    • 我有这个问题,当我调试我的代码 [ngOnChanges] 时,它在 currentValue 中给出正确的值,但它会将旧值打印到 html
    • 你能在 stackblitz 上分享它吗?相反,您可以使用我的 @Input() 更改的 setter 方法,然后自己更新属性的最新值
    猜你喜欢
    • 1970-01-01
    • 2018-05-01
    • 2020-11-30
    • 2016-09-18
    • 2019-07-20
    • 1970-01-01
    • 2021-10-03
    • 2019-06-15
    • 2020-01-02
    相关资源
    最近更新 更多