2

尝试输入属性绑定时,我将属性设置为未定义。带输入的组件:like.component.ts `

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

@Component({
  selector: 'like',
  templateUrl: './like.component.html',
  styleUrls: ['./like.component.css']
})
export class LikeComponent{
  @Input('is-liked') isLiked: boolean;
  @Input('likes-count') likesCount: number;


  onClick(){
    console.log("clicked");
    console.log(this.likesCount);
    console.log(this.isLiked);
    this.likesCount += (this.isLiked) ? -1 : 1;
    this.isLiked = !this.isLiked;

  }

}

`like.component.html

<p>
  likes work
</p>
<span class="glyphicon glyphicon-heart"
      [class.highlighted]="isLiked"
      (click)=onClick()></span>
<span>{{ likesCount }}</span>

app.component.ts

import { Component } from '@angular/core';
import { LikeComponent } from './like/like.component';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

    isSelected = true;
    likesCount = 5;


}

app.component.html

<like 
[likes-count]="likesCount"
[is-liked]="isSelected"
></like>

我在 Like 组件中声明输入属性,然后在应用程序组件中绑定它们 - 但似乎没有传递值: 开发者工具控制台

4

2 回答 2

1

在 app.module.ts 我有

 bootstrap: [AppComponent, LikeComponent]

并将其更改为:

 bootstrap: [AppComponent]

现在属性按预期绑定。

于 2018-05-21T16:35:27.380 回答
0

你应该有

<like 
[likescount]="likesCount"
[isliked]="isSelected"
></like>

 @Input() isLiked: boolean;
 @Input() likesCount: number;

DEMO STACKBLITZ

于 2018-05-21T15:58:19.317 回答