动态创建的组件了解某些输入 属性 变化的正确方法是什么?
what is the correct way for a dynamically created component to know about the change of some input property?
我正在动态创建一个组件,并将值传递给在创建的组件中定义的输入。像这样
componentRef = viewContainerRef.createComponent<ChildComponent(ChildComponent);
componentRef.instance.organization = this.selectedOrganization;
子组件看起来像这样
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss'],
})
export class ChildComponent implements OnInit, OnChanges {
@Input() organization?: OrganizationModel;
constructor() {}
ngOnInit(): void {
console.log(this.organization);
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
}
这工作正常。但是我要求子组件知道父组件中 selectedOrganization
属性 的值何时发生变化。
动态创建的组件了解某些输入更改的正确方法是什么 属性?
提前致谢
您可以在 parent
中使用“getter”
componentRef:any;
_organization:any;
get organization()
{
return this._organization
}
set organization(value)
{
this._organization=value;
if (this.componentRef)
componentRef.instance.organization=value
}
我正在动态创建一个组件,并将值传递给在创建的组件中定义的输入。像这样
componentRef = viewContainerRef.createComponent<ChildComponent(ChildComponent);
componentRef.instance.organization = this.selectedOrganization;
子组件看起来像这样
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.scss'],
})
export class ChildComponent implements OnInit, OnChanges {
@Input() organization?: OrganizationModel;
constructor() {}
ngOnInit(): void {
console.log(this.organization);
}
ngOnChanges(changes: SimpleChanges): void {
console.log(changes);
}
}
这工作正常。但是我要求子组件知道父组件中 selectedOrganization
属性 的值何时发生变化。
动态创建的组件了解某些输入更改的正确方法是什么 属性?
提前致谢
您可以在 parent
中使用“getter”componentRef:any;
_organization:any;
get organization()
{
return this._organization
}
set organization(value)
{
this._organization=value;
if (this.componentRef)
componentRef.instance.organization=value
}