1
votes

I have this template in app.component.html:

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

'data' is a json object property like:

let data = {hello : "ciao"}

This is my test.component.ts:

import { Component, OnInit, Input } from '@angular/core';

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


  @Input()
  someInput:string

  constructor() { }


  ngOnInit() {

  }

}

This is my test.component.html template:

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

I think someInput will be replace with 'data' json propery name, and my browser will display "ciao",but i dont know where to place definition of "let data ={hello:ciao} ?

IFi place in .ts, Chrome console give me an error:

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
1- Get rid of @Input() someInput:string. 2- Write this data = {hello : "ciao"} WITHOUT LET instead of the line you've got rid of in step 1. 3_ Use this instead the one in your code <p>{{data.hello}},test works!</p>M Fuat

1 Answers

0
votes

To pass a value as an @Input you need to do it in the HTML of the PARENT COMPONENT (the component that's using your test.component)

It should look like this

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

parent.component.ts

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

  constructor() {}
}