0

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

1 回答 1

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

于 2017-08-19T03:49:27.810 回答