我有一个绑定到子组件中的属性,我想将该属性用作子组件中方法的值。
我让子组件在模板中显示属性(estate.name),但出现控制台错误,即在子组件的getEstateBlocks()方法中未定义“ id”属性。
这是父组件的模板:
<h3>Managed Estates</h3>
<div>
<ul>
<li *ngFor="let estate of estates" (click)="onSelectEstate(estate)">
<div>
<h4>{{estate.name}}</h4>
</div>
</li>
</ul>
</div>
<app-estate-blocks [estate]="selectedEstate"></app-estate-blocks>
这是父组件中的onSelectEstate()方法:
onSelectEstate(estate: Estate) {
this.selectedEstate = estate;
}
这是子组件模板:
<div *ngIf="estate">
<h2>Blocks in {{estate.name}}</h2>
<ul >
<li *ngFor="let block of blocks">
<a >
<span>BLOCK</span> {{block.blockName | uppercase}}
</a>
</li>
</ul>
</div>
这是子组件中的代码:
@Component({
selector: 'app-estate-blocks',
templateUrl: './estate-blocks.component.html',
styleUrls: ['./estate-blocks.component.css']
})
export class EstateBlocksComponent implements OnInit {
@Input() estate: Estate;
blocks: Block[];
constructor(private estateService: EstatesService) { }
ngOnInit() {
this.getBlocks();
}
getBlocks() {
return this.estateService.getEstateBlocks(this.estate.id)
.subscribe(blocks => this.blocks = blocks);
}
我希望单击某个遗产后,所选遗产的块会显示在遗产列表下方。
答案 0 :(得分:0)
问题在于您在设置属性之前正在使用该属性
在这里,您使用的是this.estate
,但是,因为它在ngOnInit
生命周期挂钩中,所以当您在HTML中写入<app-estate-blocks>
时就会触发它
// this will get instantly executed
ngOnInit() {
this.getBlocks();
}
避免在设置estate-block
之前渲染selectedEstate
组件可以解决此问题
<ng-container *ngIf="selectedEstate">
<app-estate-blocks [estate]="selectedEstate"></app-estate-blocks>
</ng-container>