【问题标题】:Can't Bind Property in Angular 4无法在 Angular 4 中绑定属性
【发布时间】:2017-08-19 03:38:24
【问题描述】:

为什么在同一个组件上绑定一个属性会出现问题?我已经添加了 Input() 但仍然无法正常工作。即使绑定时它在同一个组件上,我是否需要放置 Input()?

//output.component.ts
import { Component, OnInit} from '@angular/core';
import { DataService } from '../data.service';
@Component({
  selector: 'app-output',
  templateUrl: './output.component.html',
  styleUrls: ['./output.component.css']
})
export class OutputComponent implements OnInit {
data: {name: string};
datas = [];

constructor(private dataService: DataService) { }

ngOnInit(){
   this.datas = this.dataService.datas;
}
}



//output.component.html
<p *ngFor="let data of datas"></p>
<p>{{data.name}}</p>


//data.service.ts
export class DataService {
  datas= [];

  addData(name: string){
     return this.datas.push({name: name});
  } 
}

【问题讨论】:

  • 如果您已经使用输入数据,则无需再次从服务中获取数据,
  • @Sajeetharan。我删除了 Input() 但仍然没有绑定
  • 发布您的服务代码
  • @Sajeetharan。请检查
  • 你到底想用[data]="data做什么?您希望看到什么?

标签: javascript angular data-binding angular2-services property-binding


【解决方案1】:

对于相同的组件@input API 不是必需的。当您想将数据从父组件传递给子组件时使用它。

//output.component.html
<p *ngFor="let data of dataService.datas" >  // removed [data]="data" and added dataService.datas
   <p>{{data?.name}}</p>
</p>                                         //changed the position of </p>


export class OutputComponent implements OnInit {
   constructor(private dataService: DataService) {}
}

export class DataService {
   datas= [];

   addData(name: string){
      return this.datas.push({name: name});   //return keyword was missing
   } 
}

仅供参考

演示:https://plnkr.co/edit/XlJM2LHFwlAYpQe2ancM?p=preview

【讨论】:

  • 是的。在您回答时发布!
  • 试试这个{{data?.name}} 并告诉我。
  • @micronyks。没有错误,但它不会在浏览器中输出任何内容
  • 是的。您需要添加数据。所以点击添加按钮或尝试添加数据并查看。
  • @micronyks。我做了并将console.log放在“this.datas”中的output.component.ts上,它里面有数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 2017-12-06
  • 2018-02-11
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 2018-02-24
相关资源
最近更新 更多