【问题标题】:Angular 7 @input property 'selected' does not exist on type '{}'类型'{}'上不存在Angular 7 @input属性'selected'
【发布时间】:2019-09-06 02:20:03
【问题描述】:

我是 Angular 的新手。我想以角度询问@Input("data") detailData = {};。当我console.log(detailData) 时,它会输出这样的数据。

Object { category: "dictionary", entityCategory: null, iconName: "dictionaryD", detail: {…}, key: "dictionary-7" }

当我单击console.log(detailData) 中的按钮时,它会显示为这样

Object { category: "dictionary", entityCategory: null, iconName: "dictionaryD", detail: {...}, key: "dictionary-7", selected: true }

这意味着,当我点击按钮时,它会添加selected: true,但当我console.log(detailData.selected) 时,它会出现

错误 TS2339:类型“{}”上不存在属性“selected”。

当我console.log(detailData.selected) 没有出现错误时,我该怎么做才能使其正常工作。

添加组件代码

    export class ResultDetailsComponent implements OnInit {


      @Input("data") detailData = {};
      @Output() expand = new EventEmitter();
      private expanded = false;
      constructor() {}
    // console.log(this.detailData)
      ngOnInit() {

       console.log(this.detailData)}
        if (detailData) {

          detailData.scrollIntoView()
         }
}

注意: 但是在 HTML 页面中,当我 {{detailData.selected}} 它出来 True

希望大家能帮帮我。

【问题讨论】:

  • @Input() detailData : any;
  • @rosiejaneenomar 感谢您的评论.. 当我更改为@Input() detaiData : any 时,console.log 它出来undefined
  • 你能分享一下你的组件是如何绑定的吗?
  • @rosiejaneenomar 我已经分享了我的组件代码

标签: angular typescript


【解决方案1】:

你可以试试console.log(detailData['selected'])

【讨论】:

  • 感谢您的回答.. 但它出来了undefined
【解决方案2】:

它只与 detailData 的类型有关,当您设置 detailData 属性而不定义它的类型时,打字稿将推断值的类型基数,例如 a = 10 类型的 a 将是一个数字,但是在这里,您将值设置为没有任何属性的空对象,因此类型将被推断为没有任何属性的空对象将类型设置为任何detail Data : any = {} 将解决问题,或者您可以创建结构或类的接口基础,并在声明实例化新对象。

将类型设置为任意

@Input("data") detailData : any = {}; 

设置接口类型

export interface DataDetail {
  category?: string
  entityCategory?: string,
  iconName?:string, 
  detail?: any, 
  key?:string, 
  selected?:boolean
}

组件

@Input("data") detailData : DataDetail = {};  

【讨论】:

  • @Pravu 很乐意为您提供帮助?
猜你喜欢
  • 1970-01-01
  • 2019-05-18
  • 1970-01-01
  • 2018-07-12
  • 2018-05-01
  • 1970-01-01
  • 2022-07-23
  • 2023-03-18
  • 2021-04-02
相关资源
最近更新 更多