3

I have a simple app that fetches data from sample API. Trying to figure out whats wrong when defining a directive as a component:

app.ts

import {Component, View, bootstrap, For} from 'angular2/angular2'; import {ArticlesSvc} from 'services/articlesSvc'; import {ArticleItem} from 'directives/ArticleItem'; @Component({ selector: 'main-app', injectables: [ArticlesSvc] }) @View({ template: `<p *for="#post of posts">{{ post.title }} <article-item [body]="post.body"></article-item></p>`, directives: [For,ArticleItem] }) class MainComponent { posts: Array<string>; constructor(articlesSvc: ArticlesSvc) { this.posts = []; articlesSvc.get('http://jsonplaceholder.typicode.com/posts').then((data) => { this.posts = data; }); } } bootstrap(MainComponent); 

And here is ArticleItem component:

import {Component, View} from 'angular2/angular2'; @Component({ selector: 'article-item', properties: ['body'] }) @View({ template: `<p>{{ body }}</p>` }) export class ArticleItem { body:string; } 

For some reason, it gives me Unexpected number error. How to properly connect these two components? And is it a proper way to define a sub-components with its own view?

1 Answer 1

2

I think the issue is when you try to bind the properties in your child component, you are setting an array instead of an object. So as it tries to create the setter for the bound properties, it iterates through the value (iterableChanges) provided for the properties key of Component but in your case it is an array instead of object so creating a setter for the index, ex: "0" fails.

i.e try:

@Component({ selector: 'article-item', properties: {body: 'body'} //<-- Here }) 

Another note, probably a typo(and irrelevant for this example): Your main component class' post property is declared as of type Array<string> instead of probably Array<Post> (just to be type safe :) ):

interface Post extends ArticleItem{//or even class Post title: string; } 

Plnkr

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

2 Comments

Wow, thanks! Declaring property as an object is actually worked. Angular 2 is just not completely documented for now, I guess. And about types: Is there such type as Post?
@user3115144 there are no Post built in type. You create a custom type.. thats what i meant.. Check out my example too.. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.