【问题标题】:Why would my Input Property Binding not work? - Angular为什么我的输入属性绑定不起作用? - 角
【发布时间】:2018-10-31 07:51:10
【问题描述】:

尝试输入属性绑定时,我将属性设置为未定义。 带输入的组件: 像.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 组件中声明了输入属性,然后将它们绑定到应用程序组件中 - 但似乎没有传递值: Developer Tools Console

【问题讨论】:

    标签: angular property-binding


    【解决方案1】:

    你应该有

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

    和

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

    DEMO STACKBLITZ

    【讨论】:

    • 这对我也不起作用。我看到一些帖子,你应该避免在 HTML 中使用驼峰式大小写,但这就是我开始的。
    • 我在最后附上了一张来自开发者工具的控制台输出截图。我没有使用过 stackblitz,但稍后会继续使用。
    • @Vikas 我刚刚添加了组件交互部分,逻辑OP不得不死
    • 这是因为我在带有“AppComponent”的引导程序中列出了“LikeComponent”。感谢您的演示!我将来会使用 stackblitz。所以改变 bootstrap: [AppComponent, LikeComponent] -> bootstrap: [AppComponent] 解决了这个问题。
    【解决方案2】:

    在 app.module.ts 我有

     bootstrap: [AppComponent, LikeComponent]
    

    并将其更改为:

     bootstrap: [AppComponent]
    

    现在属性按预期绑定。

    【讨论】:

      猜你喜欢
      • 2016-07-05
      • 1970-01-01
      • 2017-11-24
      • 2016-10-06
      • 1970-01-01
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 2013-09-09
      相关资源
      最近更新 更多