简体   繁体   English

@Input()返回[object Object]打字稿Angular2

[英]@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]. 当我使用@Input并尝试console.log时,结果只是[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. 这是4个文件。

hero-card.component.ts: 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 hero-card.html

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

play.html 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] . hero="{{hero}}"将字符串化的hero传递给hero属性,这可能是导致[object Object]

Use instead [hero]="hero" if hero is not supposed to be a string. 如果hero不是字符串,请改用[hero]="hero"

{{}} interpolation is used to just print/show something on HTML page. {{}}插值用于仅在HTML页面上打印/显示某些内容。

Change your 'play.html' 更改您的“ play.html”

This is how property is binded: 这是绑定属性的方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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