angular - 如何将值分配给角度 4 中的子组件属性?
问题描述
使用 ngif 时,我无法获取子组件的元素引用。经过大量搜索后,要获取元素,需要使用查看子项而不是查看子项。问题是我能够获取子引用但无法将值分配给子属性。
这里 CorrespondenceAddressComponent 是我的子组件。我将值分配给管理人员组件-SetControlsReadModeInPerson 方法中的对应地址组件对象(AddressComponentMetadataDto)之一。在分配值或调用子组件方法时,我变得不确定。
管理人员组件:
export class ManagePersonComponent extends ManagePartyComponent implements AfterViewInit {
ngAfterViewInit(): void {
this.CurrentPartyType = CurrentPartyTypeEnum.Person;
this.GetInitialDataFromService();
this.SetControlsReadModeInPerson(this.IsReadonly);
}
SetControlsReadModeInPerson(isReadOnly: boolean): void {
this.CorrespondenceAddressComponent.AddressComponentMetadataDto.IsPostalCodeDisabled = isReadOnly;
}
ManagePartyComponent(ManagePersonComponent 的基础组件):
export class ManagePartyComponent extends ProjectPageComponentBase {
@ViewChildren(CorrespondenceAddressComponent) CorrespondenceAddressComponent: CorrespondenceAddressComponent;
}
html:
<form #form="ngForm" [ngClass]="{'form-submitted' : form.submitted }" (ngSubmit)="SaveAndNavigate()">
<toolbar [ShowSaveButton]="!IsReadonly"></toolbar>
<p-tabView [(activeIndex)]="SelectedTabIndex">
<p-tabPanel [header]="'Caption.CRM.CorrespondenceAddress' | translate">
<correspondence-address [ParentForm]="form"></correspondence-address>
</p-tabPanel>
</p-tabView>
</form>
通信地址组件:
export class CorrespondenceAddressComponent extends ProjectPageComponentBase {
AddressComponentMetadataDto= new AddressComponentMetadataDto();
ngOnInit():void {
}
}
解决方案
ViewChildren 将返回一个 QueryList,而 ViewChild 返回一个匹配项。
如果您确实需要使用 ViewChildren,请确保输入正确:
export class ManagePartyComponent extends ProjectPageComponentBase {
@ViewChildren(CorrespondenceAddressComponent)
CorrespondenceAddressComponents: QueryList<CorrespondenceAddressComponent>;
}
并将其视为可枚举:
SetControlsReadModeInPerson(isReadOnly: boolean): void {
const correspondenceAddressComponent = this.CorrespondenceAddressComponents.first;
correspondenceAddressComponent.AddressComponentMetadataDto.IsPostalCodeDisabled = isReadOnly;
}
否则,请改用 ViewChild:
export class ManagePartyComponent extends ProjectPageComponentBase {
@ViewChild(CorrespondenceAddressComponent)
CorrespondenceAddressComponents: CorrespondenceAddressComponent;
}
这样您就不需要使用可枚举的对象。如果您尝试AddressComponentMetadataDto
在 QueryList 上进行引用,您将得到未定义,并且进一步引用IsPostalCodeDisabled
未定义会给您带来错误。
我要冒昧地说这是你的问题。
这个 stackblitz 应该非常接近你想要做的事情: https ://stackblitz.com/edit/angular-jnqwma?file=src%2Fapp%2Fcomponents%2Fparent-component.ts
推荐阅读
- php - 如何在 mysql php 中使用“Group By”获取平均值
- php - Symfony REST ParamConverter 注释问题
- c# - 部署到 Azure 应用服务时无法加载文件或程序集
- ios - IOS Swift4无法滚动ScrollView
- php - 为什么我的 QR 的 png img 没有在 php 中显示
- javascript - TypeScript 对象方法和嵌套对象同名
- bootstrap-4 - HikaShop 产品菜单滚动问题
- php - Wordpress:转到分页搜索的 page/2/ 时出现问题
- javascript - 添加到购物车不起作用 - Redux - React
- c# - 币安API下单