问题
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
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
}
}
回答1:
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>
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);
}
}
来源:https://stackoverflow.com/questions/45198044/databinding-from-within-a-template-in-angular