我有一个父子组件,父组件通过@Input装饰器将对象传递给子组件。问题是子只获取父数据一次,然后在将来更改传递给子项的父属性后,该值不会更新。
答案 0 :(得分:2)
如果您想从父组件获取更新值,而不是需要在子组件中添加changeDetection: ChangeDetectionStrategy.OnPush
注意: OnPush通过比较组件输入的参考
来工作@Component({
selector: 'abc',
templateUrl: 'component.html',
changeDetection: ChangeDetectionStrategy.OnPush
})
export class childComponent {
//below get updated value every time value changes in parent
@Input() inputFromParent: string;
}
在父级中,使用子组件abc
<abc [inputFromParent]="passdata"></abc>
在父母ts this.inputFromParent = newData; //在第一个init之后完成
现在,如果您更改passdata
的值,那么它也会更改childcomponent属性中的值。
答案 1 :(得分:1)
当更新整个参考时,将更新数据。如果只更新该对象内的某些属性,则不会触发它。您需要更改传递的对象的引用。
实施例
<child [data]="myData"></child>
如果您要更新myData.name = "Test"
,则不会触发。你需要做点什么
this.myData = changedData;
解决方法可以使用DoCheck
生命周期钩子并尝试手动检查属性更改。但通常更改参考文件会更方便。
答案 2 :(得分:0)
你应该阅读change detection。
如果您想要更改父组件中的数据而其他人使用service或ngrx-store,您也可以使用redux
答案 3 :(得分:0)
您的父组件html如下:
<div>
<span (click)="expandAllClient = true "> EXPAND </span>
<span (click)="expandAllClient = false"> COLLAPSE </span>
</div>
<div>
<child-comp [expandAll]="expandAllClient"(flagChanged)="flagChanged($event)"></child-comp>
</div>
不要忘记添加:
@Input() expandAll: boolean = false; in your ts file
在子组件中,您可以直接在所有操作中使用expandall(此处),例如:
<div [ngClass]="{'openPanel': expandAll}></div>
如果您单击父组件中的EXPAND span,将在此处应用openpanel类
答案 4 :(得分:0)
在父组件更改时,子组件也更改了
您可以使用OnChanges
界面执行操作,该界面可以检测组件中的更改
在app.component.html
<app-child [name]="name"></app-child>
在child.component.html
export class ChildComponent implements OnChanges {
@Input('name') name: string
text: string
constructor() { }
// on every change of @input 'name', this method will be triggered
ngOnChanges() {
this.text = 'Hi ' + this.name
}
}
您可以在
上查看完整的工作示例https://stackblitz.com/edit/on-changes?file=src%2Fapp%2Fchild%2Fchild.component.ts
答案 5 :(得分:0)
尝试通过ngOnChanges获取更改
在子组件中使用它
ngOnChanges(changes: import("@angular/core").SimpleChanges): void {
}