[英]Can't Bind Property in Angular 4
Why is there a problem in binding a property on the same component? 为什么在同一组件上绑定属性会有问题? I already added Input() but still doesn't work. 我已经添加了Input(),但仍然无法正常工作。 Do i need to put Input() even though it is on the same component when binding? 绑定时我是否需要将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});
}
}
For same component @input API
is not required. 对于相同的组件,不需要@input API
。 It is used when you want to pass the data from Parentcomponent to a child component. 当您要将数据从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
}
}
Just for your reference 仅供参考
DEMO: https://plnkr.co/edit/XlJM2LHFwlAYpQe2ancM?p=preview 演示: https : //plnkr.co/edit/XlJM2LHFwlAYpQe2ancM? p =preview
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.