简体   繁体   English

ngIf 的行为和 angular 中的属性绑定

[英]behaviour of ngIf and property binding in angular

      <myview [myVariable]=myVariable  *ngIf="myVariable">
      </myview>

I have the above component template defined which binds myVariable property to myVariable prop of myview component.我定义了上面的组件模板,它将 myVariable 属性绑定到 myview 组件的 myVariable 属性。 If there is a change in myVariable, is the myview component supposed to reload(constructor or ngOnInit).如果 myVariable 发生变化,myview 组件是否应该重新加载(构造函数或 ngOnInit)。 Its not in my environment and thus confused if this is the expected behaviour.它不在我的环境中,因此很困惑,如果这是预期的行为。 The component is getting instantiated just once and I would like it to refresh its values after any change to myVariable in the parent component.该组件仅被实例化一次,我希望它在对父组件中的 myVariable 进行任何更改后刷新其值。

you can get that event in ngOnChanges here is the example.您可以在ngOnChanges获得该事件,这是示例。

you need to write ngOnChanges in your myview component您需要在myview组件中编写ngOnChanges

import { Component, OnInit, Input, AfterViewInit, OnChanges, SimpleChanges, ViewChild, Output, EventEmitter } from '@angular/core';
@Input() myVariable: any; 

class myViewComponent implements OnChanges, OnInit {
  ngOnChanges(changes: SimpleChanges): void { 
   console.log(changes.myVariable); // here you will get the updated value of myVariable 
  }
}

you parent component html你的父组件 html

 <myview [myVariable]="myVariable"  *ngIf="myVariable">
 </myview>

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

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