首页 > 解决方案 > 如何将值分配给角度 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 {

    }
}

标签: angulartypescriptprimeng

解决方案


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


推荐阅读