从模板中的数据绑定成角度 [英] Databinding from within a template in angular
问题描述
在一个组件中,如何为以下示例进行双向数据绑定:
我希望在相应方法中设置或取消设置dataitem.isSelected
时按钮的文本自动切换
In a component how to databind two-way for the following example:
I want the button's text to toggle automatically when I am setting or unsetting dataitem.isSelected
in the respective methods
这是channelstab.component.ts的代码
Here is the code of channelstab.component.ts
@Component({
selector: 'channels-tab',
template: `
<ListView [items]="channels$ | async" class="list-group">
<ng-template let-dataitem="item">
<Button [text]="dataitem.isSelected?'UnFollow':'follow'" (tap)="dataitem.isSelected?unfollow(dataitem):follow(dataitem)"></Button>
</ng-template>
</ListView>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ChannelsTabComponent implements OnInit {
public channels$: Observable<any>;
ngOnInit() {
this.channels$ = <any>this.someService.get('channels');
}
unfollow(dataitem) {
dataitem.isSelected = false;//not working
}
follow(dataitem) {
dataitem.isSelected = true;//not working
}
}
推荐答案
只需从此处<ng-template let-dataitem="item">
删除此部分let-dataitem="item"
:
Just remove this part let-dataitem="item"
from here <ng-template let-dataitem="item">
:
<ListView [items]="channels$ | async" class="list-group">
<ng-template>
<Button [text]="dataitem.isSelected?'UnFollow':'follow'" (tap)="dataitem.isSelected?unfollow(dataitem):follow(dataitem)"></Button>
</ng-template>
</ListView>
从ng-template
创建的
嵌入视图可以访问父组件上的属性,因此只要Angular运行更改检测,就应该对其进行更新. 这里是小矮人和模仿您情况的代码:
Embedded views that are created from the ng-template
have access to the properties on the parent component, so it should be updated whenever Angular runs change detection. Here is the plunker and the code that emulates your case:
@Component({
selector: 'test',
template: `{{name}}`
})
export class TestComponent {
@Input() name;
}
@Component({
selector: 'my-app',
template: `
<ng-template #t>
<test [name]="name"></test>
</ng-template>
<ng-container #vc></ng-container>
`,
})
export class App {
@ViewChild('vc', {read: ViewContainerRef}) vc;
@ViewChild('t', {read: TemplateRef}) t;
name:string;
constructor() {
this.name = `Angular! v${VERSION.full}`;
setTimeout(()=>{
this.name='changed';
}, 3000);
}
ngOnInit() {
this.vc.createEmbeddedView(this.t);
}
}
这篇关于从模板中的数据绑定成角度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!