gpt4 book ai didi

typescript - @Input() 返回 [object Object] Typescript Angular2

转载 作者:行者123 更新时间:2023-12-03 23:43:18 25 4
gpt4 key购买 nike

好的,我在这里找不到错误。我以前用过这段代码,它工作了,但从来没有以同样的方式。

当我使用 @Input 并尝试 console.log 结果时,我得到了 [object Object]。即使我设置它的默认值或尝试记录名称,它也会说名称未定义。这是 4 个文件。

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);
}
}

英雄卡.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}}" 将字符串化的 hero 传递给 hero 属性,这可能是导致 的原因[对象对象].

如果 hero 不应该是字符串,则使用 [hero]="hero"

关于typescript - @Input() 返回 [object Object] Typescript Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38433414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com