【问题标题】:display json value as angular input @Input()将 json 值显示为角度输入 @Input()
【发布时间】:2020-05-11 14:08:37
【问题描述】:

我在 app.component.html 中有这个模板:

<test [someInput]="data"></test>

'data' 是一个 json 对象属性,例如:

let data = {hello : "ciao"}

这是我的 test.component.ts:

从'@angular/core'导入{组件,OnInit,输入};

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent implements OnInit {


  @Input()
  someInput:string

  constructor() { }


  ngOnInit() {

  }

}

这是我的 test.component.html 模板:

<p>{{someInput.hello}},test works!</p>

我认为 someInput 将被替换为 'data' json 属性名称,我的浏览器将显示“ciao”,但我不知道该放在哪里 “让数据={hello:ciao}”的定义?

.ts 中的 IFi 位置,Chrome 控制台给我一个错误:

TestComponent.html:1 ERROR TypeError: Cannot read property 'hello' of undefined
    at Object.eval [as updateRenderer] (TestComponent.html:1)
    at Object.debugUpdateRenderer [as updateRenderer] (core.js:45294)
    at checkAndUpdateView (core.js:44277)
    at callViewAction (core.js:44637)
    at execComponentViewsAction (core.js:44565)
    at checkAndUpdateView (core.js:44278)
    at callViewAction (core.js:44637)
    at execComponentViewsAction (core.js:44565)
    at checkAndUpdateView (core.js:44278)
    at callWithDebugContext (core.js:45632)

【问题讨论】:

  • 1- 摆脱@Input() someInput:string。 2- 写这个 data = {hello : "ciao"} WITHOUT LET 而不是你在步骤 1 中删除的那行。 3_ 用这个代替你代码中的那行

    {{ data.hello}},测试成功!

标签: angular typescript


【解决方案1】:

要将值作为@Input 传递,您需要在父组件(使用您的 test.component 的组件)的 HTML 中进行操作

应该是这样的

<! -- some html here -->
<app-test [someInput]="helloData">

parent.component.ts

export class ParentComponent {
  helloData = {hello: 'ciao'}

  constructor() {}
}

【讨论】:

  • 另外,如果你想传递一个对象,带有装饰器@Input的变量类型必须是Object或任何类型。
猜你喜欢
  • 2018-09-28
  • 2014-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 2016-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多