繁体   English   中英

无法在Angular 4中绑定属性

[英]Can't Bind Property in Angular 4

为什么在同一组件上绑定属性会有问题? 我已经添加了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});
  } 
}

对于相同的组件,不需要@input API 当您要将数据从Parentcomponent传递到子组件时使用。

//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

暂无
暂无

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

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