角度模板内的数据绑定 [英] Databinding from within a template in angular

查看:17
本文介绍了角度模板内的数据绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个组件中如何对以下示例进行双向数据绑定:当我在各自的方法中设置或取消设置 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
     }
}

推荐答案

从这里移除这部分 let-dataitem="item" <ng-template let-dataitem="项目">:

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 运行更改检测,就应该更新它.这是 plunker 和模拟您案例的代码:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆