Why is my Angular template throwing this Typescript error?

社会主义新天地 提交于 2019-12-09 22:49:52

问题


I'm building an Angular 4 project in Typescript 2.3.4. I can't figure out what's wrong with the code below.

IDialog interface

export interface IDialog{
    cancellable?: boolean,     

    inputs?: Array<{label: string, value?: any, description?: string}|string>
    message: string
    title?: string,
    type?: DialogInputTypes // <- an Enum
}

SampleComponent.ts

  public dialog:IDialog = {
    cancellable:false,
    title:'Dialog Title',
    message:'This is a modal dialog',
    type:DialogInputTypes.button,
    inputs:[
      {label:'OK', value:'OK'},
      {label:'Cancel', value:'Cancel'}
    ]
  };

SampleComponent.html

<input *ngFor="let input of dialog.inputs" [value]="input.value">
                                                    ^^^^^^^^^^^^

This error is thrown by the compiler:

Angular: Identifier 'value' is not defined. <anonymous> does not contain such a member

I just upgraded from Angular 2 with Typescript 2.0 and this error was not present before.

Why is this error thrown? Perhaps it has to do with the fact that IDialog.inputs is defined as either an array or a string, and at compile time there is no way for the compiler to know which shape inputs has. If I remove |string from the interface, the error goes away.

More importantly, I don't know how to fix my code.


回答1:


Its definitely your project configuration Your code works perfectly fine if its like this

@Component({
   template: `
       <input *ngFor="let input of dialog.inputs" [value]="input.value">
   `
})
export class WhateverComponent{
    public dialog:IDialog = {
        inputs:[
            {label:'OK', value:'OK'},
            {label:'Cancel', value:'Cancel'}
        ]
    };
}
export interface IDialog{
    inputs: Array<iSomeControl | string >;
}
export interface iSomeControl{
    label: string;
    value: string;

}

I am using Angular 4.0.2 Typescript 2.2.2 I modified in order to be more specific




回答2:


Disable angular extension pack and angular language service plugins from VS code.

I had a similar problem and this solved it.



来源:https://stackoverflow.com/questions/44915015/why-is-my-angular-template-throwing-this-typescript-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!