无法在 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
不是必需的。当你想将数据从父组件传递到子组件时使用。
//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
}
}
仅供参考
为什么在同一组件上绑定 属性 会出现问题?我已经添加了 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
不是必需的。当你想将数据从父组件传递到子组件时使用。
//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
}
}
仅供参考