2

I'm trying to pass an object to a component in an angular template:

<note-setting
  *ngFor="let setting of settings"
  [settingData]="setting"
></note-setting>

how do I do this correctly? the setting that is declared in the *ngFor should be passed in the [settingData] field to the note-setting component.

I don't understand why this is so difficult to figure out, I've been using react for 3 years and it's so much simpler, I just do:

settings.map(setting => <NoteSetting settingData={setting} />)

Also, every angular tutorial I've seen only shows how to pass primitive types like ints and strings.

1 Answer 1

2

You have to declare settingData as an @Input property in the note-setting component. You can check the bound value in ngOnInit.

export class NoteSettingComponent implements OnInit {

  @Input() settingData: SettingData; // use the appropriate type here

  ngOnInit() {
    console.log(this.settingData);
  }
}

See this stackblitz for a demo.

Sign up to request clarification or add additional context in comments.

6 Comments

i already did that, that's not my question. My question is about the right way to structure the code I showed at the top - is the syntax right?
I don't see any problem with the syntax in your code snippet. If you declared the @Input property, it probably already works. Does it?
no it's showing me undefined for the settingData, I'm comparing the stackblitz to my code now
What about settings in the parent component? Is that an array of objects?
strangely, in the note-setting component's html template, the settingData renders correctly, but in the constructor of the component ts file, it keeps saying undefined. This is what my constructor looks like: constructor() { console.log('data', this.settingData); } which is why I thought it wasn't working
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.