简体   繁体   中英

@Input() returns [object Object] Typescript Angular2

Okay, I can't find the error here. I've used this code before and it worked, but never in the same way.

When I use @Input and try to console.log the result I just get [object Object]. Even when I set its default or try to log the name, it says the name is undefined. Here are the 4 files.

hero-card.component.ts:

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

@Component({
    selector: 'hero-card',
    templateUrl: 'app/views/play/hero-card/hero-card.html'
})
export class HeroCard {
    @Input() hero = {name : 'loading'};
    printHero(){
        console.log(this.hero);
    }
}

hero-card.html

<div class="hero-card" (click)="printHero()">
<h1>Hero</h1>
<p>{{hero.name}}</p>
</div>

play.html

<button class="btn btn-default" [routerLink]="['/home']">Quit</button>
<div *ngIf="loaded">
<hero-card hero="{{hero}}"></hero-card>
</div>

play.ts

import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { HeroCard } from './hero-card/hero-card.component';
import { Shaman } from "../../lib/heros/shaman/hero.shaman";

@Component({
    selector: 'play',
    templateUrl: 'app/views/play/play.html',
    directives: [ROUTER_DIRECTIVES, HeroCard],
    styles: []
})
export class Play {
    hero: any;
    loaded: boolean;

    load(){
        this.hero = new Shaman();
        console.log(this.hero);
        this.loaded = true;
    }

    ngOnInit():void {
        this.loaded = false;
        this.load();
    }
}

hero="{{hero}}" passes the stringified hero to the hero property which is probably what leads to [object Object] .

Use instead [hero]="hero" if hero is not supposed to be a string.

{{}} interpolation is used to just print/show something on HTML page.

Change your 'play.html'

This is how property is binded:

<hero-card [hero]="hero"></hero-card>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM