Angular 2组件编译报错:Property 'socials' does not exist on type 'any[]'
嘿,这个错误一看就是模板遍历逻辑搞混了,我来帮你快速捋清楚~
问题根源
你的socialSharing变量是数组类型(Array<any>),但在模板里直接写了socialSharing.socials——这就相当于你在问「数组本身有没有socials属性」,而数组对象本身根本没有这个属性。正确的逻辑应该是:先取数组里的单个配置对象,再访问这个对象的socials属性。
看你在setMethod里的赋值:
this.socialSharing = [{ containerId: 'social-sharing-preview', showLabel: false, socials: ['linkedin', 'twitter'] }];
socialSharing是一个包含单个配置对象的数组,所以模板得先遍历数组拿到配置对象,再遍历对象里的socials数组。
修复后的模板代码
把你的Test.Component.html改成下面这样:
<!-- 先遍历socialSharing数组,拿到每个配置项 --> <div *ngFor="let config of socialSharing"> <!-- 再遍历当前配置项的socials数组 --> <div *ngFor="let social of config.socials; let i = index;"> <div class="gig-button-container gig-button-container-{{social}}"> <div id="social-sharing-preview-reaction{{i}}" class="gig-button-up" title="" alt=""> <button [attr.data-social]="social" <!-- 修正class绑定的语法,用config对象的showLabel属性 --> class="social-sharing-btn {{config.showLabel ? 'with-label' : ''}}" (click)="socialShare(social)" > <span class="icon icon_{{social}}"></span> <!-- 修正翻译管道的语法,确保表达式正确 --> <span style="font-size:13px;">{{config.showLabel ? ('Share on ' + social | translate) : ''}}</span> </button> </div> </div> </div> </div>
额外优化(可选但推荐)
为了避免any类型带来的潜在问题,你可以给socialSharing定义明确的类型:
// 在组件类上方定义接口 interface SocialSharingConfig { containerId: string; showLabel: boolean; socials: string[]; } // 然后修改socialSharing的类型声明 socialSharing: SocialSharingConfig[];
这样TypeScript会帮你做类型检查,后续修改代码时能提前发现错误。
内容的提问来源于stack exchange,提问作者santosh kumar patro
相关产品推荐
相关产品推荐

