Ant's
Ant's

Reputation: 13811

How do I pass data between components in Angular 2?

I have a component on Angular 2.47 alpha version, which was looking like this:

@Component({
    selector: 'app',
    template: `
      <div class="col-md-4" *ngFor="#data of datas">
        <OtherComponent [dataDetails]="data"></OtherComponent>
        <br />
      </div>
    </div>
  `
})
export class App {
    datas: Array<Object> = [];
}

The code was working properly; The data is been passed to OtherComponent as expected on a loop. But until I tried moving to angular 2 beta version, it stopped working and started to throw this error:

Can't bind to 'dataDetails' since it isn't a known native property ("

Have I made a mistake?

Upvotes: 1

Views: 2670

Answers (2)

drew moore
drew moore

Reputation: 32670

There are three possible issues here, two of which have been mentioned:

  • OtherComponent needs to be declared in directives on App
  • dataDetails needs to be declared in inputs on OtherComponent

Assuming both of those are true, are you certain that OtherComponent is being loaded before App? If not, you need to use forwardRef:

Replace:

@Component({
    selector: 'app',
    template: `...`,
    directives: [OtherComponent]
})

with:

@Component({
    selector: 'app',
    template: `...`,
    directives: [forwardRef(()=>OtherComponent) OtherComponent] //untested syntax
})

Upvotes: 1

pe8ter
pe8ter

Reputation: 1263

You need to inform Angular 2 that OtherComponent exists. Assuming the class has the same name, this is what your Component decorator should look like:

@Component({
    selector: 'app',
    template: `...`,
    directives: [OtherComponent]
})

Unrelated, custom tag names shouldn't be camel-case, they should be kebab-case. When they land in the DOM they become lowercase, which is inconsistent with your code. Also, custom tag names are supposed to have at least one dash in them.

Upvotes: 0

Related Questions