当我将其用作组件时,我的列表没有正确更新,但是当我直接在父级中添加模板时,它可以正常工作。有人有什么建议吗?
如果我离开页面然后回来,它会正确加载它 当我将console.log添加到bankaccount-list组件中的订阅时,当我添加新的银行帐户时,它会正确更新。
这是父html。
<div class="card-block card-list">
<search-box (update)="term = $event"></search-box>
<bankaccounts-list (update)="setSelectedBankAccount($event)"></bankaccounts-list>
<!--template from below component entered here works, but when done like this it doesnt-->
</div>
这是在父
中添加的组件@Component({
selector: 'bankaccounts-list',
moduleId: module.id,
directives: [NgClass],
template: `
<div class="list-group scroll-list">
<div class="card" *ngFor="let bankAccount of bankAccounts>
<div class="card-header">
{{bankAccount.name}}
</div>
<div class="card-block">
{{bankAccount.description}}<br />
</div>
</div>
</div>
`
})
export class BankAccountListComponent implements OnInit {
@Output() update = new EventEmitter();
bankAccounts: any = [];
constructor(public userDetailsService: UserDetailsService) {
}
ngOnInit() {
this.userDetailsService.bankAccounts
.subscribe((data:any) => {
this.bankAccounts = data;
});}
}
更多信息:
我使用第三个组件添加新帐户,该组件以模态加载。
它在userDetailsService
private _bankAccounts: BehaviorSubject<any[]> = new BehaviorSubject(<any>[]);
bankAccounts = this._bankAccounts.asObservable();
newBankAccount(acnt: any) {
let bank = this._bankAccounts.getValue();
bank.push({
'id': Math.floor((Math.random() * 50) + 1),
'name':acnt.name,
'description':acnt.desc,
'bankAccountName':acnt.acnt_name,
'bankAccountBsb':acnt.bsb,
'bankAccountNumber':acnt.num
});
this._bankAccounts.next(bank);
}
答案 0 :(得分:0)
export class BankAccountListComponent implements OnInit {
@Output() update = new EventEmitter();
bankAccounts: any = [];
constructor(private cd: ChangeDetectorRef,
public userDetailsService: UserDetailsService) {
}
ngOnInit() {
this.userDetailsService.bankAccounts
.subscribe((data:any) => {
this.bankAccounts = data;
this.cd.markForCheck();
});}
}
我将markForCheck添加到了订阅中,它现在通过完整的组件树而不是像之前的hapening一样在父组件上工作。